Are base calls dynamically bound in c#? - c#

Just out of curiosity: are calls using the base keyword in C# dynamically bound (i.e. is it a polymorphic call)?
Consider the following example:
public class A
{
public virtual void WriteSomething()
{
Console.WriteLine("Hello from A");
}
}
public class B : A
{
public override void WriteSomething()
{
base.WriteSomething();
Console.WriteLine("Hello from B");
}
}
public class Program
{
public static void Main()
{
A instance = new B();
instance.WriteSomething();
}
}
I know that when a client (in this example the Main method) calls instance.WriteSomething, this call is dynamically bound. But what about the base.WriteSomething call in the overridden method in class B? I assume that it is not dynamically bound because the compiler knows the base class at compile time and therefore Dynamic Binding is not necessary - but I couldn't find any documentation on that.
Thanks for your help in advance!

Well I just had a look at the Intermediate Language and there one can see that the base call is not dynamically bound (the blue rectangle):

Related

C# call interface method implemented in many classes without having instance to those classes

Sample Code
using System;
public interface MyInterface
{
void MyMethod();
}
public class A:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from A");
}
}
public class B:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from B");
}
}
public class C:MyInterface
{
void MyInterface.MyMethod()
{
Console.WriteLine("Hello World from C");
}
}
public class Program
{
public static void Main()
{
C obj = new C();
MyInterface iface=(MyInterface)obj;
iface.MyMethod(); // This will print "Hello World from C"
}
}
The Problem
The Sample code I given above shows the method I used for calling interface method in my project, In the code I have an interface called MyInterface and it has a method called MyMethod(), In current sample I called the interface method using object of Class C, In my project I will have more classes that needs to implement MyInterface and the My method in all these classes need to be called at once.
Take an Example
Currently I have classes A,B,C and all of them have MyMethod() with Different function body, then later I added another class D and I need to call MyMethod() in all classes at the same time, the number of classes might be 100's, so is there any way to call all MyMethod() without creating object for 100's of classes.
A possible solution is to use Polymorphism. You can have a method like this:
public static void ExecuteMyMethods(IEnumerable<MyInterface> instances)
{
foreach(var instance in instances) instance.MyMethod();
}
It will be working for you as needed and you will not have to modify it when new implementation of MyInterface occurs. You will have to pass the new instance from the caller side.
You can also wrap & isolate the logic of getting the collection of MyInterface implementations somewhere, to have it in a single place & once new implementation comes around, you will know where to create an instance of it, for this method to work properly. You can consider using Factory method pattern for that.

Concept of C# polymorphism

Below code:
public class Program
{
static void Main(string[] args)
{
father f = new son(); Console.WriteLine(f.GetType());
f.show();
}
}
public class father
{
virtual public void show()
{
Console.WriteLine("father");
}
}
public class son : father
{
public override void show()
{
Console.WriteLine("son");
}
}
The result is 'son'.
If I modify the 'public override void show()' to 'public new void show()',the result is 'father'.
So I conclude below 'rules':
Use 'override', which function will be called is determined in run
time. The program will choose the right function according to the
real type of current object.(As above, the f's runtime type is son,
so it calls the son's show.)
Use 'new' modifier, which function will be called is determined when
it is compiled.The program will choose the object's declared type to
call its function.(As above, the f's declared type is father ,so
using 'new' modifier make the output to show 'father'.
All above are what I understand about polymorphism.Any misunderstanding and wrong?
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
Not really. The decision is still made at execution time, but the new method does not override the virtual method in the base class. This is most easily shown by extending your example somewhat:
using System;
class Base
{
public virtual void Foo()
{
Console.WriteLine("Base.Foo");
}
}
class Derived : Base
{
public override void Foo()
{
Console.WriteLine("Derived.Foo");
}
}
class MoreDerived : Derived
{
public new void Foo()
{
Console.WriteLine("MoreDerived.Foo");
}
}
class Test
{
static void Main()
{
Base x = new MoreDerived();
x.Foo(); // Prints Derived.Foo
}
}
Here, at compile time the decision is made to call the most overridden implementation of Base.Foo - if there were multiple Foo signatures, the decision about which signature to use would be taken, for example. Which implementation will be "the most overridden" is unknown at this point, of course.
At execution time, the CLR will find that most overridden implementation based on the actual type of the target object - which is MoreDerived. But MoreDerived.Foo doesn't override Base.Foo... whereas Derived.Foo does, so the implementation in Derived is the one which is actually executed.
Use 'new' modifier, which function will be called is determined when it is compiled.The program will choose the object's declared type to call its function.(As above, the f's declared type is father ,so using 'new' modifier make the output to show 'father'.
This is slightly wrong. Using new means that this function does not override any functions of the base class. The function dispatch still happens at runtime, but this function is not considered. The difference would be clearer if you had Grandson or Daughter classes to test more.
yes it work like that only...your understanding is right..
But for second case when you use new intad of override it hide actual implementation i.e. parent class implementation
As the new keyword was used to define this method, the derived class method is not called—the base class method is called instead.
EXample from MSDN
// Define the base class
class Car
{
public virtual void DescribeCar()
{
System.Console.WriteLine("Four wheels and an engine.");
}
}
// Define the derived classes
class ConvertibleCar : Car
{
public new virtual void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("A roof that opens up.");
}
}
class Minivan : Car
{
public override void DescribeCar()
{
base.DescribeCar();
System.Console.WriteLine("Carries seven people.");
}
}
call to the class
Car[] cars = new Car[3];
cars[0] = new Car();
cars[1] = new ConvertibleCar();
cars[2] = new Minivan();
output
Car object: YourApplication.Car
Four wheels and an engine.
----------
Car object: YourApplication.ConvertibleCar
Four wheels and an engine.
----------
Car object: YourApplication.Minivan
Four wheels and an engine.
Carries seven people.
----------
MSDN having good example of it : Knowing When to Use Override and New Keywords (C# Programming Guide)
A normal method is called by type of class and a virtual method is called by content of memory allocated to the object. Now keyword new hides the concept of polymorphic and just care for its type.

Force base method call

Is there a construct in Java or C# that forces inheriting classes to call the base implementation? You can call super() or base() but is it possible to have it throw a compile-time error if it isn't called? That would be very convenient..
--edit--
I am mainly curious about overriding methods.
There isn't and shouldn't be anything to do that.
The closest thing I can think of off hand if something like having this in the base class:
public virtual void BeforeFoo(){}
public void Foo()
{
this.BeforeFoo();
//do some stuff
this.AfterFoo();
}
public virtual void AfterFoo(){}
And allow the inheriting class override BeforeFoo and/or AfterFoo
Not in Java. It might be possible in C#, but someone else will have to speak to that.
If I understand correctly you want this:
class A {
public void foo() {
// Do superclass stuff
}
}
class B extends A {
public void foo() {
super.foo();
// Do subclass stuff
}
}
What you can do in Java to enforce usage of the superclass foo is something like:
class A {
public final void foo() {
// Do stuff
...
// Then delegate to subclass
fooImpl();
}
protected abstract void fooImpl();
}
class B extends A {
protected void fooImpl() {
// Do subclass stuff
}
}
It's ugly, but it achieves what you want. Otherwise you'll just have to be careful to make sure you call the superclass method.
Maybe you could tinker with your design to fix the problem, rather than using a technical solution. It might not be possible but is probably worth thinking about.
EDIT: Maybe I misunderstood the question. Are you talking about only constructors or methods in general? I assumed methods in general.
The following example throws an InvalidOperationException when the base functionality is not inherited when overriding a method.
This might be useful for scenarios where the method is invoked by some internal API.
i.e. where Foo() is not designed to be invoked directly:
public abstract class ExampleBase {
private bool _baseInvoked;
internal protected virtual void Foo() {
_baseInvoked = true;
// IMPORTANT: This must always be executed!
}
internal void InvokeFoo() {
Foo();
if (!_baseInvoked)
throw new InvalidOperationException("Custom classes must invoke `base.Foo()` when method is overridden.");
}
}
Works:
public class ExampleA : ExampleBase {
protected override void Foo() {
base.Foo();
}
}
Yells:
public class ExampleB : ExampleBase {
protected override void Foo() {
}
}
I use the following technique. Notice that the Hello() method is protected, so it can't be called from outside...
public abstract class Animal
{
protected abstract void Hello();
public void SayHello()
{
//Do some mandatory thing
Console.WriteLine("something mandatory");
Hello();
Console.WriteLine();
}
}
public class Dog : Animal
{
protected override void Hello()
{
Console.WriteLine("woof");
}
}
public class Cat : Animal
{
protected override void Hello()
{
Console.WriteLine("meow");
}
}
Example usage:
static void Main(string[] args)
{
var animals = new List<Animal>()
{
new Cat(),
new Dog(),
new Dog(),
new Dog()
};
animals.ForEach(animal => animal.SayHello());
Console.ReadKey();
}
Which produces:
You may want to look at this (call super antipatern) http://en.wikipedia.org/wiki/Call_super
If I understand correctly you want to enforce that your base class behaviour is not overriden, but still be able to extend it, then I'd use the template method design pattern and in C# don't include the virtual keyword in the method definition.
No. It is not possible. If you have to have a function that does some pre or post action do something like this:
internal class Class1
{
internal virtual void SomeFunc()
{
// no guarantee this code will run
}
internal void MakeSureICanDoSomething()
{
// do pre stuff I have to do
ThisCodeMayNotRun();
// do post stuff I have to do
}
internal virtual void ThisCodeMayNotRun()
{
// this code may or may not run depending on
// the derived class
}
}
I didn't read ALL the replies here; however, I was considering the same question. After reviewing what I REALLY wanted to do, it seemed to me that if I want to FORCE the call to the base method that I should not have declared the base method virtual (override-able) in the first place.
Don't force a base call. Make the parent method do what you want, while calling an overridable (eg: abstract) protected method in its body.
Don't think there's any feasible solution built-in. I'm sure there's separate code analysis tools that can do that, though.
EDIT Misread construct as constructor. Leaving up as CW since it fits a very limited subset of the problem.
In C# you can force this behavior by defining a single constructor having at least one parameter in the base type. This removes the default constructor and forces derived types to explcitly call the specified base or they get a compilation error.
class Parent {
protected Parent(int id) {
}
}
class Child : Parent {
// Does not compile
public Child() {}
// Also does not compile
public Child(int id) { }
// Compiles
public Child() :base(42) {}
}
In java, the compiler can only enforce this in the case of Constructors.
A constructor must be called all the way up the inheritance chain .. ie if Dog extends Animal extends Thing, the constructor for Dog must call a constructor for Animal must call a constructor for Thing.
This is not the case for regular methods, where the programmer must explicitly call a super implementation if necessary.
The only way to enforce some base implementation code to be run is to split override-able code into a separate method call:
public class Super
{
public final void doIt()
{
// cannot be overridden
doItSub();
}
protected void doItSub()
{
// override this
}
}
public class Sub extends Super
{
protected void doItSub()
{
// override logic
}
}
I stumbled on to this post and didn't necessarily like any particular answer, so I figured I would provide my own ...
There is no way in C# to enforce that the base method is called. Therefore coding as such is considered an anti-pattern since a follow-up developer may not realize they must call the base method else the class will be in an incomplete or bad state.
However, I have found circumstances where this type of functionality is required and can be fulfilled accordingly. Usually the derived class needs a resource of the base class. In order to get the resource, which normally might be exposed via a property, it is instead exposed via a method. The derived class has no choice but to call the method to get the resource, therefore ensuring that the base class method is executed.
The next logical question one might ask is why not put it in the constructor instead? The reason is that it may be an order of operations issue. At the time the class is constructed, there may be some inputs still missing.
Does this get away from the question? Yes and no. Yes, it does force the derived class to call a particular base class method. No, it does not do this with the override keyword. Could this be helpful to an individual looking for an answer to this post, maybe.
I'm not preaching this as gospel, and if individuals see a downside to this approach, I would love to hear about it.
On the Android platform there is a Java annotation called 'CallSuper' that enforces the calling of the base method at compile time (although this check is quite basic). Probably the same type of mechanism can be easily implemented in Java in the same exact way. https://developer.android.com/reference/androidx/annotation/CallSuper

How method hiding works in C#?

Why the following program prints
B
B
(as it should)
public class A
{
public void Print()
{
Console.WriteLine("A");
}
}
public class B : A
{
public new void Print()
{
Console.WriteLine("B");
}
public void Print2()
{
Print();
}
}
class Program
{
static void Main(string[] args)
{
var b = new B();
b.Print();
b.Print2();
}
}
but if we remove keyword 'public' in class B like so:
new void Print()
{
Console.WriteLine("B");
}
it starts printing
A
B
?
When you remove the public access modifier, you remove any ability to call B's new Print() method from the Main function because it now defaults to private. It's no longer accessible to Main.
The only remaining option is to fall back to the method inherited from A, as that is the only accessible implementation. If you were to call Print() from within another B method you would get the B implementation, because members of B would see the private implementation.
You're making the Print method private, so the only available Print method is the inherited one.
Externally, the new B.Print()-method isn't visible anymore, so A.Print() is called.
Within the class, though, the new B.Print-method is still visible, so that's the one that is called by methods in the same class.
when you remove the keyword public from class b, the new print method is no longer available outside the class, and so when you do b.print from your main program, it actually makes a call to the public method available in A (because b inherits a and a still has Print as public)
Without the public keyword then the method is private, therefore cannot be called by Main().
However the Print2() method can call it as it can see other methods of its own class, even if private.

C# - using polymorphism in classes I didn't write

What is the best way to implement polymorphic behavior in classes that I can't modify? I currently have some code like:
if(obj is ClassA) {
// ...
} else if(obj is ClassB) {
// ...
} else if ...
The obvious answer is to add a virtual method to the base class, but unfortunately the code is in a different assembly and I can't modify it. Is there a better way to handle this than the ugly and slow code above?
Hmmm... seems more suited to Adapter.
public interface ITheInterfaceYouNeed
{
void DoWhatYouWant();
}
public class MyA : ITheInterfaceYouNeed
{
protected ClassA _actualA;
public MyA( ClassA actualA )
{
_actualA = actualA;
}
public void DoWhatYouWant()
{
_actualA.DoWhatADoes();
}
}
public class MyB : ITheInterfaceYouNeed
{
protected ClassB _actualB;
public MyB( ClassB actualB )
{
_actualB = actualB;
}
public void DoWhatYouWant()
{
_actualB.DoWhatBDoes();
}
}
Seems like a lot of code, but it will make the client code a lot closer to what you want. Plus it'll give you a chance to think about what interface you're actually using.
Check out the Visitor pattern. This lets you come close to adding virtual methods to a class without changing the class. You need to use an extension method with a dynamic cast if the base class you're working with doesn't have a Visit method. Here's some sample code:
public class Main
{
public static void Example()
{
Base a = new GirlChild();
var v = new Visitor();
a.Visit(v);
}
}
static class Ext
{
public static void Visit(this object b, Visitor v)
{
((dynamic)v).Visit((dynamic)b);
}
}
public class Visitor
{
public void Visit(Base b)
{
throw new NotImplementedException();
}
public void Visit(BoyChild b)
{
Console.WriteLine("It's a boy!");
}
public void Visit(GirlChild g)
{
Console.WriteLine("It's a girl!");
}
}
//Below this line are the classes you don't have to change.
public class Base
{
}
public class BoyChild : Base
{
}
public class GirlChild : Base
{
}
I would say that the standard approach here is to wrap the class you want to "inherit" as a protected instance variable and then emulate all the non-private members (method/properties/events/etc.) of the wrapped class in your container class. You can then mark this class and its appropiate members as virtual so that you can use standard polymorphism features with it.
Here's an example of what I mean. ClosedClass is the class contained in the assembly whose code to which you have no access.
public virtual class WrapperClass : IClosedClassInterface1, IClosedClassInterface2
{
protected ClosedClass object;
public ClosedClass()
{
object = new ClosedClass();
}
public void Method1()
{
object.Method1();
}
public void Method2()
{
object.Method2();
}
}
If whatever assembly you are referencing were designed well, then all the types/members that you might ever want to access would be marked appropiately (abstract, virtual, sealed), but indeed this is unfortunately not the case (sometimes you can even experienced this issue with the Base Class Library). In my opinion, the wrapper class is the way to go here. It does have its benefits (even when the class from which you want to derive is inheritable), namely removing/changing the modifier of methods you don't want the user of your class to have access to. The ReadOnlyCollection<T> in the BCL is a pretty good example of this.
Take a look at the Decorator pattern. Noldorin actually explained it without giving the name of the pattern.
Decorator is the way of extending behavior without inheriting. The only thing I would change in Noldorin's code is the fact that the constructor should receive an instance of the object you are decorating.
Extension methods provide an easy way to add additional method signatures to existing classes. This requires the 3.5 framework.
Create a static utility class and add something like this:
public static void DoSomething(this ClassA obj, int param1, string param2)
{
//do something
}
Add a reference to the utility class on the page, and this method will appear as a member of ClassA. You can overload existing methods or create new ones this way.

Categories

Resources