i have two classes which have some common methods like
funcA(), funcB()
and some methods are only related to its class...
what i did is made interface of TestInterface
public interface TestInterface
{
void funcA()
void funcB()
}
public class ClassA : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassA FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassA FuncB()");
}
public void myFuncA()
{
Console.WriteLine("This is My Own Function A");
}
}
public class ClassB : TestInterface
{
public void funcA()
{
Console.WriteLine("This is ClassB FuncA()");
}
public void funcB()
{
Console.WriteLine("This is ClassB FuncB()");
}
public void myFuncB()
{
Console.WriteLine("This is My Own Function B");
}
}
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
}
as u see in above two classes. i have two functions myFuncA() and myFuncB() are not part of interface. they only belongs to their own class.
how can i call them from the main method. where i am creating object of TestInterface and initializing it with some child class.???
actually i have separate classes in DAL.
they have some common methods. and some methods related to their own class.
i want to implement Factory Pattern on this.
what should i do now?
If you're asking whether you can do something like:
public static void Main(string[] a)
{
TestInterface test = new ClassA();
test.myFuncA();
}
the answer is no. You would have to cast it to ClassA first. The fact that you think you need to do this indicates there is probably something wrong with your design.
TestInterface test = new ClassA();
test.myFuncA();
(test as ClassB).myFuncB();
Hopefully this was what you were looking for.
Make a new interface for ClassA and ClassB and you just need to cast the class to the correct interface to see the new functions.
public class ClassA : TestInterface, TestInterfaceA {
}
So, when you get the concrete instance just cast that to TestInterfaceA to see the functions specific to this class.
You can cast the TestInterface object, but it defeats the purpose of polymorphism...
public static void main()
{
TestInterface test = new ClassA();
test.funcA();
((ClassA) test).myFuncA();
}
Try casting. I assume from the question you meant something like this:
public void simpleMethod(TestInterface variableName) {
if (variableName is ClassA) {
((ClassA)variableName).myFuncA();
}
}
Mohsen I'm really confused with your question
if you just want to call MyFuncA() or MyFuncB() just you should create an instance of their own calss like
ClassA a = new ClassA();
a.FuncA(); //interface member
a.FuncB(); // interface member
a.MyFuncA(); //class A Member
I can't undrestand why you are trying to create an instance of your Interface and then call subclass methods!!!!
Am I right ? or Imisunderstood your issue ?
is it good to add methods of ClassA and ClassB into interface and provide null implementation in other class?
like
public interface TestInterface
{
void funcA();
void funcB();
void myFuncA();
void myFuncB();
}
public class ClassA:TestInterface
{
public void funcA()
{
// some code here
}
public void funcB()
{
// some code here
}
public void myFuncA()
{
// my own code here
}
public void funcB()
{
// null implementation
}
}
and vise versa of this in ClassB
Related
using System;
interface ISample{
abstract void SampleMethod();
}
class SampleClass: ISample{
void ISample.SampleMethod(){
Console.WriteLine("SampleMethod was called.");
}
}
class Program{
public static void Main (string[] args){
SampleClass smpcls = new SampleClass();
smpcls.ISample.SampleMethod();
}
}
This code works seamlessly. But I must call "ISample" interface from "smpcls" which is the instance of "SampleClass". How can I call "SampleMethod" directly from a instance of "SampleClass"?
For example:
...
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod() //I would like to call it like this.
smpcls.ISample.SampleMethod() //Not like this
...
why don't use this
void Main()
{
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod();
}
public interface ISample
{
public void SampleMethod();
}
public class SampleClass : ISample
{
public void SampleMethod()
{
Console.WriteLine("SampleMethod was called.");
}
}
or if have c# 8+ maybe you mean this
SampleClass smpcls = new SampleClass();
smpcls.AsISampleMethod();
//or if you don't want to create an extra method
smpcls.AsISample.SampleMethod();
public interface ISample
{
void SampleMethod()
{
Console.WriteLine("SampleMethod was called.");
}
}
public class SampleClass : ISample
{
public ISample AsISample => (ISample)this;
public void AsISampleMethod()
{
AsISample.SampleMethod();
}
}
but the interface works almost the same as an abstract class
SampleClass explicitly implements ISample.SampleMethod, which is not what you want. Simply change it to
class SampleClass: ISample{
void SampleMethod(){
Console.WriteLine("SampleMethod was called.");
}
}
You must cast it as the interface to access a explicitly implemented interface method
ISample smpcls = new SampleClass();
smpcls.SampleMethod();
You have to know that when implementing an interface's members there are two ways:
implement interface
implement interface explicitely
In your example you have selected implement interface explicitely.
void ISample.SampleMethod()
If you use this option, then you are telling the class that the method void ISample.SampleMethod() belongs to the interface and NOT to the class.
Why and when can you use explicit option? Well, suppose you have another method in your class which is called exactly SampleMethod()
Now, if you implement ISample then you will have a clash with this method as ISample contains a method with the same name. So, to sovle this you use the explicit option on the interface method.
public class SampleClass : ISample
{
void ISample.SampleMethod()
{
Console.WriteLine("interface method");
}
public void SampleMethod()
{
Console.WriteLine("class method");
}
}
In your calling code, this is how you call each method:
SampleClass smpcls = new SampleClass();
smpcls.SampleMethod();
((ISample)smpcls).SampleMethod();
As you can see: ((ISample)smpcls).SampleMethod();
this belongs to the interface as you have to cast it to it.
The output from both methods will be as follows:
//class method
//interface method
If you do not have clashing methods, then use the option "implement interface" which will declare the code without the interface name:
public class SampleClass : ISample
{
public void SampleMethod()
{
Console.WriteLine("now this method belongs to the class");
}
}
I'm new to C#. I've a doubt, how can we add a method in ClassA using ClassB.
For example I've following code:
public ClassA{
method1(){}
method2(){}
}
public ClassB{
//Here i want add another method for `ClassA`
}
Is it possible?
It sounds like what you want is an extension method. The first line from the documentation says:
Extension methods enable you to "add" methods to existing types
without creating a new derived type, recompiling, or otherwise
modifying the original type.
As you mention in your comment ("They just give the class name ClassA but, not .cs file so i can't add a method in ClassA"), it sounds like you don't have access to the source code for ClassA. Using an extension method, you can make your own method that can be called for an instance of ClassA.
In the sample code below, classA.method3(); is possible:
class Program
{
static void Main(string[] args)
{
ClassA classA = new ClassA();
classA.method3(); // call the extra ClassA method you wrote
}
}
// This class is assumed to be somewhere that you cannot modify
public class ClassA
{
public void method1() { }
public void method2() { }
}
// This is "ClassB" from your question, but I've renamed it to "ExtensionMethods"
public static class ExtensionMethods
{
public static void method3(this ClassA classA) { }
}
It's unclear what exactly you want, but inheritance is a solution:
public ClassB {
public method3() {};
}
public ClassA : ClassB { // now ClassA has method3 too
method1(){}
method2(){}
}
Why we need to use new if hiding is intended, when we can directly create ClassA object and call printA method of classA
I'm confused why do we need this new keyword here when we have the option to directly create class object and call the required method:
class Program
{
static void Main()
{
classA clsA = new ClassB();
clsA.printA();
}
}
public class classA
{
public classA()
{
Console.WriteLine("ClassA constructor");
}
public void printA()
{
Console.WriteLine("ClassA-PrintA Method");
}
}
class ClassB : classA
{
public ClassB()
{
Console.WriteLine("ClassB constructor");
}
public void printB()
{
Console.WriteLine("ClassB-PrintB Method");
}
public new void printA()
{
Console.WriteLine("Class B extending ClassA.PrintA Method");
}
}
Difference between below code implementation when anyway we have to call PrintA method of class A in both the cases...
1) Using new keyword with the method in the both the base and derived class ------------------------------------------------------------------
class Program
{
static void Main()
{
classA clsA = new classA();
clsA.printA();
}
}
public class classA
{
public classA()
{
Console.WriteLine("ClassA constructor");
}
public virtual void printA()
{
Console.WriteLine("ClassA-PrintA Method");
}
}
class ClassB : classA
{
public ClassB()
{
Console.WriteLine("ClassB constructor");
}
public new void printA()
{
Console.WriteLine("Class B extending ClassA.PrintA Method");
}
}
2) Without using new keyword and no printA implementation in ClassB ----------------------------------------------------------------
class Program
{
static void Main()
{
classA clsA = new classA();
clsA.printA();
}
}
public class classA
{
public classA()
{
Console.WriteLine("ClassA constructor");
}
public void printA()
{
Console.WriteLine("ClassA-PrintA Method");
}
}
class ClassB : classA
{
public ClassB()
{
Console.WriteLine("ClassB constructor");
}
}
what is the real time need of new keyword.
new keyword requirement is there to draw your attention to the fact that the method in the parent class will be hidden and not overridden.
Hiding isn't really one of the best practices when it comes to OOP, virtual methods are more common. IMHO the developers of the c# compiler decided that if the class declares a member with the signature that is equivalent to that of any other member's down the inheritance chain, and there is no override prefix - it might be a mistake, so the compiler asks whether hiding is intentional.
You don't need the new keyword unless you wish to hide the base class member, and then you do need the keyword as that is how the C# language is designed. The code would not compile without it.
Typically, you declare a function in your base class and not redefine in the derived class, or you define the base class function virtual (can be overridden) or abstract (must be overriden).
So: ClassB could be written without any printA function at all as it is already declared in the base class and is not abstract:
class ClassB : classA
{
public ClassB()
{
Console.WriteLine("ClassB constructor");
}
public void printB()
{
Console.WriteLine("ClassB-PrintB Method");
}
}
The above will compile and printA will be callable from ClassB but will use the implementation in ClassA.
Furthermore, consider this:
classA clsA = new ClassB();
clsA.printA();
new ClassB().printA();
Output:
ClassA constructor
ClassB constructor
ClassA-PrintA Method
ClassA constructor
ClassB constructor
Class B extending ClassA.PrintA Method
Do you see that when you instantiate a ClassB but store it in a ClassA variable you get the output from the ClassA version of the function, whereas new ClassB.printA() returns the output from the ClassB version?
It sounds to me like you want to have ClassB.PrintA() output different from ClassA.PrintA(), but you want to be able to call ClassA.PrintA() from an instance of ClassB too. You can do it by declaring ClassA.PrintA() as virtual:
public class classA
{
public virtual void printA()
{
Console.WriteLine("ClassA-PrintA Method");
}
}
and overriding the function in ClassB:
class ClassB : classA
{
public void printB()
{
Console.WriteLine("ClassB-PrintB Method");
}
public override void printA()
{
Console.WriteLine("Classb-PrintA Method");
// Let's also call the ClassA version, just to show you how it works
base.printA();
}
}
And just to prove the point, we've called the ClassA version too using the base keyword.
void Main()
{
new ClassB().printA();
}
Console output:
Classb-PrintA Method
ClassA-PrintA Method
Let's say I have a class Abc:
class Abc {
}
and that I'd like to externally add some method m() to it. I guess it's probably possible to do this, although I am not sure how. Assuming it is possible to do that, let's then say Abc does have, from now on, a m() method.
Now, imagine I have other class Def:
class Def {
public void x(Abc abc) {
abc.m();
}
}
Would this code run with PostSharp? To the more distracted reader, the problem with this is that in a standard C# class program, our compiler might not know the Abc class has a m() method.
My gut feeling is that this wouldn't work with PostSharp. Am I mistaken?
(Maybe you can use the DLR to accomplish if my PostSharp solutions aren't sufficient?)
Yes you can. You would use introducemember attribute in an instance scoped aspect. Your best bet is to implement an interface using postshsrp then reference your target class as that interface to expose the method. You can also use Post.Cast<>() to access it at design time.
Here are two methods to do this. The first is via an interface, the second is using stubs.
Method 1 - Interface
public class Program
{
static void Main(string[] args)
{
Customer c = new Customer();
var cc = Post.Cast<Customer, ISomething>(c);
cc.SomeMethod();
}
}
public interface ISomething
{
void SomeMethod();
}
[AddMethodAspect]
public class Customer
{
}
[Serializable]
[IntroduceInterface(typeof(ISomething))]
public class AddMethodAspect : InstanceLevelAspect, ISomething
{
#region ISomething Members
public void SomeMethod()
{
Console.WriteLine("Hello");
}
#endregion
}
Method 2 - stubs
public class Program
{
static void Main(string[] args)
{
Customer c = new Customer();
c.SomeMethod();
}
}
[AddMethodAspect]
public class Customer
{
public void SomeMethod() { }
}
[Serializable]
public class AddMethodAspect : InstanceLevelAspect
{
[IntroduceMember(OverrideAction = MemberOverrideAction.OverrideOrFail)]
public void SomeMethod()
{
Console.WriteLine("Hello");
}
}
More Info
Just in case there are some issues with using the Cast<>() function, it doesn't do an actual cast. The compiled result looks like:
private static void Main(string[] args)
{
Customer c = new Customer();
ISomething cc = c;
cc.SomeMethod();
}
You can do it if the class is in a different assembly.
On the other hand, if the classes are in the same module, then you are right, the C# compiler won't compile it. Why not implement m() like this in C#, then replace the implementation with PostSharp?
class Abc
{
public void m()
{
throw new NotImplementedException ();
}
}
Edit:
What if you put m() in an interface, then use PostSharp to implement the interface on your class? Then you can call the method by casting to that interface.
interface IM
{
void m();
}
class Def {
public void x(Abc abc) {
if (abc is IM)
((IM) abc).m();
}
}
This question seems weird, but i came across this question in one of the interviews recently.
I ve been asked, is there a way in c# to hide the methods partially in a inherited child classes?. Assume the base class A, exposed 4 methods. Class B implements A and it will only have the access to first 2 methods and Class C implements A will only have the access to last 2 methods.
I know we can do this way
public interface IFirstOne
{
void method1();
void method2();
}
public interface ISecondOne
{
void method3();
void method4();
}
class baseClass : IFirstOne, ISecondOne
{
#region IFirstOne Members
public void method1()
{
throw new NotImplementedException();
}
public void method2()
{
throw new NotImplementedException();
}
#endregion
#region ISecondOne Members
public void method3()
{
throw new NotImplementedException();
}
public void method4()
{
throw new NotImplementedException();
}
#endregion
}
class firstChild<T> where T : IFirstOne, new()
{
public void DoTest()
{
T objt = new T();
objt.method1();
objt.method2();
}
}
class secondChild<T> where T : ISecondOne, new()
{
public void DoTest()
{
T objt = new T();
objt.method3();
objt.method4();
}
}
But what they wanted is different. They wanted to hide these classes on inheriting from baseclasses. something like this
class baseClass : IFirstOne, ISecondOne
{
#region IFirstOne Members
baseClass()
{
}
public void method1()
{
throw new NotImplementedException();
}
public void method2()
{
throw new NotImplementedException();
}
#endregion
#region ISecondOne Members
public void method3()
{
throw new NotImplementedException();
}
public void method4()
{
throw new NotImplementedException();
}
#endregion
}
class firstChild : baseClass.IFirstOne //I know this syntax is weird, but something similar in the functionality
{
public void DoTest()
{
method1();
method2();
}
}
class secondChild : baseClass.ISecondOne
{
public void DoTest()
{
method3();
method4();
}
}
is there a way in c# we can achieve something like this...
I did it by having 1 main base class and 2 sub bases.
// Start with Base class of all methods
public class MyBase
{
protected void Method1()
{
}
protected void Method2()
{
}
protected void Method3()
{
}
protected void Method4()
{
}
}
// Create a A base class only exposing the methods that are allowed to the A class
public class MyBaseA : MyBase
{
public new void Method1()
{
base.Method1();
}
public new void Method2()
{
base.Method2();
}
}
// Create a A base class only exposing the methods that are allowed to the B class
public class MyBaseB : MyBase
{
public new void Method3()
{
base.Method3();
}
public new void Method4()
{
base.Method4();
}
}
// Create classes A and B
public class A : MyBaseA {}
public class B : MyBaseB {}
public class MyClass
{
void Test()
{
A a = new A();
// No access to Method 3 or 4
a.Method1();
a.Method2();
B b = new B();
// No Access to 1 or 2
b.Method3();
b.Method4();
}
}
Although you can't do exactly what you want, you could use explicit interface implementation to help, in which the interface members are only exposed if it is explicitly cast to that interface...
Perhaps the interviewer may have been referring to method hiding?
This is where you declare a method with the same signature as on in your base class - but you do not use the override keyword (either because you don't or you can't - as when the method in the base class is non-virtual).
Method hiding, as opposed to overriding, allows you to define a completely different method - one that is only callable through a reference to the derived class. If called through a reference to the base class you will call the original method on the base class.
Don't use inheritance. It makes the public or protected facilities of the base class available directly in the derived class, so it simply isn't want you want.
Instead, make the derived class implement the relevant interface, and (if necessary) forward the methods on to a private instance of the underlying class. That is, use composition (or "aggregation") instead of inheritance to extend the original class.
class firstChild : IFirstOne
{
private baseClass _owned = new baseClass();
public void method1() { _owned.method1(); }
// etc.
}
By the way, class names should start with an upper case letter.
There is 2 solutions to hide methods inherited from a base class:
As mentioned by thecoop, you can explicitely implement the interface declaring the methods you want to hide.
Or you can simply create these methods in the base class (not inherited from any interface) and mark them as private.
Regards.
What about injecting base class as an IFirst?
interface IFirst {
void method1();
void method2();
}
interface ISecond {
void method3();
void method4();
}
abstract class Base : IFirst, ISecond {
public abstract void method1();
public abstract void method2();
public abstract void method3();
public abstract void method4();
}
class FirstChild : IFirst {
private readonly IFirst _first;
public FirstChild(IFirst first) {
_first = first;
}
public void method1() { _first.method1(); }
public void method2() { _first.method2(); }
}
Injection keeps you from violating the Interface Segregation Principle. Pure inheritance means that your FirstChild is depending on an interface that it doesn't use. If you want to retain only the IFirst functionality in Base, but ignore the rest of it, then you cannot purely inherit from Base.