How to call base method from derived class instance in C#? - c#

I have C# code, base class A and derived class B:
public class A
{
public virtual void print() {Console.WriteLine("a"); }
}
public class B:A
{
public override void print() { Console.WriteLine("b"); }
}
static void Main(string[] args)
{
A a= new B();
//In c++ I can use .Base:: to call base method from derived class instance
a.Base::print();
}
I can't modify these two classes and I don't know what can I do in C#, any suggestion?
Additionally, thanks to everyone joining into this discussion, and I would like to clarify why I need this behavior:
In .net framework, we have an interface IPostBackDataHandler to handle postback. and in there is a method
public bool LoadPostData( string postDataKey, NameValueCollection postCollection )
When I implement it and test, I find sometimes the given postback type of postCollection is NameValueCollection ,while other time it's HttpValueCollection (a derived class of NameValueCollection)
Then,if it is a type of HttpValueCollection, when I get item from it, eg. postCollection['ControlID'] and I input html in this control, HttpValueCollection.get_item() will always validate the input and view it as a defect. While NameValueCollection.get_item() won't
I don't want it operate validation automatically, at least I should decide whether it should be validated, should I?

There is no way to access base method from outside the derived class.
You can either write a method in derived class that will call base method like this:
public class B : A
{
public override void print() { Console.WriteLine("B"); }
public void basePrint() { base.print(); }
}
Or you can user Reflection to get base method definition and invoke it but it's rather ugly.
Here is how to create DynamicMethod that calls base print method:
// Get MethodInfo of the base method
var methodInfo = typeof(A).GetMethod("Print", BindingFlags.Instance | BindingFlags.Public);
// Create DynamicMethod based on the methodInfo
var dynamicMethod = new DynamicMethod("BasePrint", methodInfo.ReturnType, new[] { methodInfo.DeclaringType }, methodInfo.DeclaringType);
// Create ILGenerator for the dynamic method
var il = dynamicMethod.GetILGenerator();
// Emit argument with index 0 - DeclaringType
il.Emit(OpCodes.Ldarg_0);
// Emit method call
il.EmitCall(OpCodes.Call, methodInfo, null);
// Emit method return value
il.Emit(OpCodes.Ret);
// Invoke method with target...
var b = new B();
dynamicMethod.Invoke(null, new object[] {b});
// ... or create a delegate and invoke method without target
var action = dynamicMethod.CreateDelegate(typeof(Action)) as Action;
action.Invoke();
Note that it'll work only for parameterless method. If you want to call method with parameters you'll have to put their types into the array with the DeclaringType and later emit all of them. Also you'll have to create delegate of type Action<parameterTypes or Func<returnType, parameterTypes> if the method returns something.

You can only call your base class's methods from the derived class (B) by doing:
base.print();
I don't think there is a way to do what you want to do, because it kind of breaks the point of polymorphism.
However, you can hide the print method in A by doing this in B:
new public void print() { Console.WriteLine("b"); }
This way, this code:
A a= new B();
a.print();
will call the print in A.

Thanks to everyone!
Finally I realize this behavior need using reflection and delegate, like nocodename showing, here I find a similar method.
A a = new B();
var ptr = typeof(A).GetMethod("Print", new[] { typeof(_inputParameter) }).MethodHandle.GetFunctionPointer();
var baseGetItem = (Func<String, String>)Activator.CreateInstance(typeof(Func<String, String>), a, ptr);
String postedValue = baseGetItem(_parameter);

You can't call base print outside of a class B i.e. from Main method due to way how override works in c#. However if you want to have possibility to do that, you should consider to shadow print method in class B:
public class B:A
{
public new void print() { Console.WriteLine("b"); }
}
With new keyword class shadows member from parent class, so your line of code will work:
A a= new B();
a.print(); //prints "a"
and
B b= new B();
b.print(); //prints "b"

The whole idea of override is that you will not call the base class's function.
If you want to call A.print - use A object, if you want to call B.print use B object, and if you want an object that can use some of that and some of that - create it separately or use functions with different names, that might solve your problem.
I'm not sure what you are trying to accomplish here, but maybe you would like to read about Visitor Pattern
Good Luck!

You can simply call base class method from derived class by using "base" keywork:
see example,
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
B obj= new B();
obj.print();
Console.ReadKey();
}
}
public class A
{
public virtual void print() { Console.WriteLine("a"); }
}
public class B : A
{
public override void print()
{
base.print();
Console.WriteLine("b");
}
}
}
hope you understand! Thank u

You cannot call the base method when you override it in the inherited. You can make the method in B to be new instead of override, but you lose the implementation.
public class A
{
public virtual void Print() { Console.WriteLine("a"); }
}
public class B: A
{
public new void Print() { Console.WriteLine("b"); }
}
This way when you call
static void Main(string[] args)
{
A a = new B();
a.Print(); // prints "a"
}
Otherwise, you can call base.Print() in the overridden method.
public class A
{
public virtual void Print() { Console.WriteLine("a"); }
}
public class B: A
{
public override void Print()
{
base.Print();
Console.WriteLine("b");
}
}

var obj = new B();
obj.Print(); // overriden method
(obj as A).Print(); // base method

Related

Polymophism in C#, how to turn parent object into a child object in a method?

public class Program
{
public static void Main()
{
var type = new C().getType();
type.Foo();
}
public class A
{
public void Stop()
{
// do something
}
}
public class B : A
{
public void Foo()
{
Console.WriteLine("Foo");
}
}
public class D : A
{
public void Bar()
{
Console.WriteLine("Bar");
}
}
public class C
{
public A getType()
{
if (some condition)
return new B();
if (some condition)
return new D();
return A();
}
}
}
-EDIT-
I updated the code, so now we have two child classes B and D, both have different methods inside them, however since they inherit A, they at least both have access to Stop() method. The problem with making an abstract method Foo() and Bar() inside the parent class A is that, B should not have access to Bar() and D should not have access to Foo(), but by making an abstract method they will need to implement them both.
I know that I can check the type of the returned object inside Main() method and then cast it to that type. But this won't be convenient as in the future I will have more descendants of A.
Is it in my situation ok, to use dynamic? Because that would solve the problem and would be very convenient.
public class C
{
public dynamic getType()
{
if (some condition)
return new B();
if (some condition)
return new D();
return A();
}
}
You almost had it right:
public class Program
{
public static void Main()
{
var type = new C().getType();
type.Foo();
}
public abstract class A
{
public abstract void Foo();
}
public class B : A
{
public override void Foo()
{
Console.WriteLine("Foo");
}
}
public class C
{
public A getType()
{
return new B();
}
}
}
You need a Foo method in A that B can override. I have made A.Foo abstract, which means we do not have to define a base implementation of A.Foo. The A class is declared abstract to prevent someone trying to create an instance of it.
If you want derived classes to inherit a base implementation of Foo from A, then declare Foo as virtual in A. So in the following example, class B overrides the base Foo, whereas class C inherits the base Foo:
public class Program
{
public static void Main()
{
A a1 = new B();
a1.Foo(); // Outputs "B.Foo".
A a2 = new C();
a2.Foo(); // Outputs "A.Foo".
}
public abstract class A
{
public virtual void Foo()
{
Console.WriteLine("A.Foo");
}
}
public class B : A
{
public override void Foo()
{
Console.WriteLine("B.Foo");
}
}
public class C : A
{
}
}
You are confusing the type of a variable and the type of the runtime object it will be pointing to (given its a reference type, with value types, there is no such distinction).
When you declare a variable, you are defining the type of the variable:
Foo a = ... //a is of type Foo at compile time.
What you assign to that variable doesn't matter at all (unless you are using implicitly typed variables with var)
But given the following code:
object o = new Foo();
Now you can see the diferrence; the variable o is of type object but the runtime object it will be pointing to is of type string.
In your question you are asking why you cant do the following:
var stringLength = o.Length; //o is a string isn't it?
Why? Isn't o really a string. Yes, but that information is only availabe at runtime, the compiler knows nothing of what will happen at runtime, it only knows that o is of type object and object has no Length property. The only thing the compiler will make sure of is that the types are compatible; it will let you assign a Giraffe to an Animal typed variable but it won't let you assing a Car.
If you've got this clear, then you'll understando why this doesn't make sense:
But I did explicitly return B inside getType() method, why does it not have access to Foo()?
Because the method getType return type is A not B, not C and not D.

Why in this code the output of the virtual functions is like this? [duplicate]

What are differences between declaring a method in a base type "virtual" and then overriding it in a child type using the "override" keyword as opposed to simply using the "new" keyword when declaring the matching method in the child type?
I always find things like this more easily understood with pictures:
Again, taking joseph daigle's code,
public class Foo
{
public /*virtual*/ bool DoSomething() { return false; }
}
public class Bar : Foo
{
public /*override or new*/ bool DoSomething() { return true; }
}
If you then call the code like this:
Foo a = new Bar();
a.DoSomething();
NOTE: The important thing is that our object is actually a Bar, but we are storing it in a variable of type Foo (this is similar to casting it)
Then the result will be as follows, depending on whether you used virtual/override or new when declaring your classes.
The "new" keyword doesn't override, it signifies a new method that has nothing to do with the base class method.
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
public class Test
{
public static void Main ()
{
Foo test = new Bar ();
Console.WriteLine (test.DoSomething ());
}
}
This prints false, if you used override it would have printed true.
(Base code taken from Joseph Daigle)
So, if you are doing real polymorphism you SHOULD ALWAYS OVERRIDE. The only place where you need to use "new" is when the method is not related in any way to the base class version.
Here's some code to understand the difference in the behavior of virtual and non-virtual methods:
class A
{
public void foo()
{
Console.WriteLine("A::foo()");
}
public virtual void bar()
{
Console.WriteLine("A::bar()");
}
}
class B : A
{
public new void foo()
{
Console.WriteLine("B::foo()");
}
public override void bar()
{
Console.WriteLine("B::bar()");
}
}
class Program
{
static int Main(string[] args)
{
B b = new B();
A a = b;
a.foo(); // Prints A::foo
b.foo(); // Prints B::foo
a.bar(); // Prints B::bar
b.bar(); // Prints B::bar
return 0;
}
}
The new keyword actually creates a completely new member that only exists on that specific type.
For instance
public class Foo
{
public bool DoSomething() { return false; }
}
public class Bar : Foo
{
public new bool DoSomething() { return true; }
}
The method exists on both types. When you use reflection and get the members of type Bar, you will actually find 2 methods called DoSomething() that look exactly the same. By using new you effectively hide the implementation in the base class, so that when classes derive from Bar (in my example) the method call to base.DoSomething() goes to Bar and not Foo.
Beyond just the technical details, I think using virtual/override communicates a lot of semantic information on the design. When you declare a method virtual, you indicate that you expect that implementing classes may want to provide their own, non-default implementations. Omitting this in a base class, likewise, declares the expectation that the default method ought to suffice for all implementing classes. Similarly, one can use abstract declarations to force implementing classes to provide their own implementation. Again, I think this communicates a lot about how the programmer expects the code to be used. If I were writing both the base and implementing classes and found myself using new I'd seriously rethink the decision not to make the method virtual in the parent and declare my intent specifically.
virtual / override tells the compiler that the two methods are related and that in some circumstances when you would think you are calling the first (virtual) method it's actually correct to call the second (overridden) method instead. This is the foundation of polymorphism.
(new SubClass() as BaseClass).VirtualFoo()
Will call the SubClass's overriden VirtualFoo() method.
new tells the compiler that you are adding a method to a derived class with the same name as a method in the base class, but they have no relationship to each other.
(new SubClass() as BaseClass).NewBar()
Will call the BaseClass's NewBar() method, whereas:
(new SubClass()).NewBar()
Will call the SubClass's NewBar() method.
The difference between the override keyword and new keyword is that the former does method overriding and the later does method hiding.
Check out the folllowing links for more information...
MSDN and Other
new keyword is for Hiding. - means you are hiding your method at runtime. Output will be based base class method.
override for overriding. - means you are invoking your derived class method with the reference of base class. Output will be based on derived class method.
My version of explanation comes from using properties to help understand the differences.
override is simple enough, right ? The underlying type overrides the parent's.
new is perhaps the misleading (for me it was). With properties it's easier to understand:
public class Foo
{
public bool GetSomething => false;
}
public class Bar : Foo
{
public new bool GetSomething => true;
}
public static void Main(string[] args)
{
Foo foo = new Bar();
Console.WriteLine(foo.GetSomething);
Bar bar = new Bar();
Console.WriteLine(bar.GetSomething);
}
Using a debugger you can notice that Foo foo has 2 GetSomething properties, as it actually has 2 versions of the property, Foo's and Bar's, and to know which one to use, c# "picks" the property for the current type.
If you wanted to use the Bar's version, you would have used override or use Foo foo instead.
Bar bar has only 1, as it wants completely new behavior for GetSomething.
Not marking a method with anything means: Bind this method using the object's compile type, not runtime type (static binding).
Marking a method with virtual means: Bind this method using the object's runtime type, not compile time type (dynamic binding).
Marking a base class virtual method with override in derived class means: This is the method to be bound using the object's runtime type (dynamic binding).
Marking a base class virtual method with new in derived class means: This is a new method, that has no relation to the one with the same name in the base class and it should be bound using object's compile time type (static binding).
Not marking a base class virtual method in the derived class means: This method is marked as new (static binding).
Marking a method abstract means: This method is virtual, but I will not declare a body for it and its class is also abstract (dynamic binding).
using System;
using System.Text;
namespace OverrideAndNew
{
class Program
{
static void Main(string[] args)
{
BaseClass bc = new BaseClass();
DerivedClass dc = new DerivedClass();
BaseClass bcdc = new DerivedClass();
// The following two calls do what you would expect. They call
// the methods that are defined in BaseClass.
bc.Method1();
bc.Method2();
// Output:
// Base - Method1
// Base - Method2
// The following two calls do what you would expect. They call
// the methods that are defined in DerivedClass.
dc.Method1();
dc.Method2();
// Output:
// Derived - Method1
// Derived - Method2
// The following two calls produce different results, depending
// on whether override (Method1) or new (Method2) is used.
bcdc.Method1();
bcdc.Method2();
// Output:
// Derived - Method1
// Base - Method2
}
}
class BaseClass
{
public virtual void Method1()
{
Console.WriteLine("Base - Method1");
}
public virtual void Method2()
{
Console.WriteLine("Base - Method2");
}
}
class DerivedClass : BaseClass
{
public override void Method1()
{
Console.WriteLine("Derived - Method1");
}
public new void Method2()
{
Console.WriteLine("Derived - Method2");
}
}
}

If derived class does not override the method,which version should be called?

I am trying understand the need of override and virtual in C#,so I wrote the following code:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I was expecting "Derived method" to be called and printed.Then I wrote the following code without using virtual/override combination.
using System;
namespace Override
{
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
d.method();
}
}
}
And I got the same result i.e. "Derived method" called and printed.My question is if the code worked without virtual/override as I expected,what is the need of them? or am I missing something here?
In your source code, you are always doing simple inheritance without any polymorphic behavior. You are always created instance of derived class and assigning it to derived class instance variable.
DerivedClass d = new DerivedClass(); // here no polymorphism, and only inheritance is there
So When you will call method using class variable, it will always call DerivedClass method, no matter if the method is virtual or not in parent class.
In Polymorphism, your programs do not know the exact type of class on which you are calling the method (this concept is called late-binding). As in example below:
BaseClass b = new DerivedClass(); // here b is a base class instance but initiated using derived class
After calling b.method() it will do late binding and will show polymorphic behavior (only if the method has been set virtual in the base class)
NOTE: The virtual keyword delays binding to correct version of method to runtime and is core keywork to implement polyphorphism. So for exact polymorphic behavior, declare methods as virtual in parent class, and then in child class, ovverride that method.
virtual allows the correct version of the method to be chosen at runtime, based on information not available at compile time. Consider the following tweak to your example:
using System;
namespace Override
{
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d = new Derived();
Base b = d;
b.method();
}
}
}
With virtual/override, this code will display Derived method, as at runtime we can see that b is really a Derived instance. Without virtual/override, it will display Base method, as the declared type of b is Base.
Here is the test you are missing:
Base d = new Derived();
d.method(); // "Derived method"
Base b = new Base();
b.method(); // "Base method"
Also imagine if you had a collection of Base objects that were composed of different inherited objects. The virtual keyword allows those Base objects to understand what type they really are at runtime.
List<Base> collection = new List<Base>();
collection.Add(new Base());
collection.Add(new Derived()};
collection.Add(new Base());
foreach(Base b in collection)
{
b.method(); // will print out "Base" or "Derived" correctly
}
see the DIFFERENCE
class Base
{
public void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Derived method
class Base
{
public virtual void method()
{
Console.WriteLine("Base method");
}
}
class Derived : Base
{
public override void method()
{
Console.WriteLine("Derived method");
}
}
class Program
{
static void Main(string[] args)
{
Derived d;
d = new Derived();
d.method();
d = new Base();
d.method();
}
}
OUTPUT :
Derived method
Base method
Base class pointers can be used to point to object of the base class or any object derived from the base. So the need of virtual methods come into picture when base class object point to derived class
Base d = new Derived();
d.method(); // "Derived method"
The method 'method' on the Derived class will hide the implementation of the Base class which is why you got the messaged "Derived method".
There are many uses of virtual and abstract but one example is where you have functionality in the base class which may not fit all cases of classes that inherit from your base class. Using virtual allows another class to completely override that functionality and provide its own implementation.

Polymorphism/Overriding

Could someone please explain what the difference is between these two examples?
Class A
protected virtual string GetData()
Class B
private override string GetData()
And the following:
Class A
protected string GetData()
Class B
private string GetData()
Assuming that 'Class B' inherits from 'Class A'.
I always assumed that you need to use virtual in the superclass and override in the subclass if you want overriding of a method, however I tried removing the keywords and the program compiled fine. What exactly is the difference, if any?
The second example that you showed hides the GetData of the parent, it doesn't override it.
Example:
private class Base
{
public virtual void Test()
{
Console.WriteLine("Base");
}
public void Test2()
{
Console.WriteLine("Base");
}
}
private class Derived : Base
{
public override void Test()
{
Console.WriteLine("Derived");
}
public void Test2()
{
Console.WriteLine("Derived");
}
}
static void Main()
{
Base b = new Base();
Derived d = new Derived();
Base dInB = new Derived();
b.Test();
d.Test();
dInB.Test();
b.Test2();
d.Test2();
dInB.Test2();
Console.ReadKey(true);
}
It outputs:
Base // Base.Test()
Derived // Derived.Test()
Derived // Derived.Test()
Base // Base.Test2()
Derived // Derived.Test2()
Base // You think you're calling Derived.Test2(), but you actually call Base.Test2()
Actually this sample is invalid, because it should use the new keyword in public new void Test2() in the Derived class.
It works just like operator overloading. It doesn't actually override anything. When you have the exact type Derived it calls the new method.
You have to be really careful with hiding members, it is nothing like overriding (classes) or implementing (interfaces) at all. Only when you have the exact type it'll call a new method, otherwise it'll still call the base type's method!
The difference is that in the first case you are overriding and in the second case you are hiding which is completely different.
In the first case:
class B: A
{
void Foo()
{
B b = new B();
A a = b;
a.GetData() //B's GetData() will be called
b.GetData() //B's GetData() will be called
}
}
On the other hand in the second case:
class B: A
{
void Foo()
{
B b = new B();
A a = b;
a.GetData() //A's GetData() will be called
b.GetData() //B's GetData() will be called
}
}
In the second case you are simply hiding A's implementation of GetData() but you will always be able to call A's implementation through a variable typed A even if the variable refers to a instance of type B. Note that this is completely different from how overriding behaves.
public class A
{
public virtual string GetData() { return "A";}
}
public class B : A
{
public override string GetData() { return "B"; }
}
What do you expect if you are using the classes as in the following codeblock?
A a = new A();
B b = new B();
A c = new B();
Console.WriteLine(a.GetData());
Console.WriteLine(b.GetData());
Console.WriteLine(c.GetData());
This will print "A" "B" "B". The variable c is stored as A type but when executing the method the code is resolved to the "real" implementation. (see google for virtual function table and resolving principle)
If you do not use virtual and override as in the code below this will print "A" "B" "A".
public class A
{
public string GetData() { return "A";}
}
public class B : A
{
public new string GetData() { return "B"; }
}

C# static method from object

I have various objects of different types.
For all of them, I want to call a static method of their class. All the classes share the same method.
How can I call this static method without explicitly calling the class?
You could accomplish this by putting a method in each object that calls the corresponding static method. However, the fact that you want to do this suggests that your design might be able to be improved. If you'd tell us what you're trying to accomplish, someone may be able to suggest a better approach.
If these classes all extend the same base class, then calling the method on the base class will work.
For example:
public class Base
{
public static DoSomething()
{
//something
}
}
public class A: Base
{
}
public class B: Base
{
}
The following method calls execute the same code:
A.DoSomething();
B.DoSomething();
Base.DoSomething();
You want to call every method on each of the individual classes? You have to call them explicitly, referencing each class individually.
Does the static method for every class have the same common code? Put it into a static class for use by all of the other classes, or create one or more extension methods.
Are you looking for something like you have something like List<object> where all of the objects are guaranteed to have a static method named, say MethodX() ?
If so you could reflect on them, look for the method name, and execute that.
Either that or inheritance like the others mention (which would be the correct way to go).
If you need to have a specific implementation for each type, I don't think a static method is the right approach... Instead, you shoud define an interface implemented by all your classes. You can then call the instance method defined by the interface on each object :
public interface IDoSomething
{
void DoSomething();
}
public class A: IDoSomething
{
public void DoSomething()
{
// implementation for A
}
}
public class B: IDoSomething
{
public void DoSomething()
{
// implementation for B
}
}
Of course, if you don't need a specific implementation for each type, then you can just call Base.DoSomething (as explained by David)
I'm not sure what exactly you're trying to do. But using my imagination I come up with this implementation.
internal class Program
{
private static void Main(string[] args)
{
var staticMethodClasses = new List<StaticMethodClassBase>
{new ClassA(), new ClassB()};
foreach (StaticMethodClassBase item in staticMethodClasses)
{
Type t = item.GetType();
MethodInfo staticMethod =
t.GetMethod("DoSomething", BindingFlags.Static | BindingFlags.Public);
staticMethod.Invoke(null, null);
}
}
}
public abstract class StaticMethodClassBase
{
}
public class ClassA : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class A");
}
}
public class ClassB : StaticMethodClassBase
{
public static void DoSomething()
{
Console.WriteLine("Class B");
}
}

Categories

Resources