How Overloading is Compile Time and Overriding is Runtime? - c#

Folks
I came across many threads for understanding polymorphism (Both compile time and run time). I was surprised to see some links where the programmers are claiming Overloading is Runtime and Overriding is compile time.
What I want to know from here is:
Runtime Polymorphism with a REAL TIME example and small code and what scenario we should use.
Compile time Polymorphism with REAL TIME example and small code and when to use.
Because I read many theoretical definitions, but I am not satisfied in understanding that.
Also, I gave a thought, that where I also felt, overloading should be runtime as because, say I have a method that calculates Area, at runtime only it decides which overloaded method to call based on parameters I pass (Say if I pass only one parameter, it should fire Square, and if parameters are 2, it should fire Rectangle)....So isn't it I can claim its runtime ? How its complie time ? (Most say theoretically, overloading is compile time but they dont even give a correct REAL time example...very few claim its runtime)....
Also, I feel overriding is compile time because, while you write code and complie, you ensure you used virtual keyword and also overriding that method in derived class which otherwise would give you compile time error. So I feel its compile time, the same way where I saw in a thread.....But most threads claims its runtime :D
I am confused :( This question is additional to my question 1 and 2. Please help with a real time example.. as I am already aware of theoretical definitions .... :(
Thank you....

In the case of Overloading, you are using static (compile-time) polymorphism because the compiler is aware of exactly which method you are calling. For example:
public static class test
{
static void Main(string[] args)
{
Foo();
Foo("test");
}
public static void Foo()
{
Console.WriteLine("No message supplied");
}
public static void Foo(string message)
{
Console.WriteLine(message);
}
}
In this case, the compiler knows exactly which Foo() method we are calling, based on the number/type of parameters.
Overriding is an example of dynamic (runtime) polymorphism. This is due to the fact that the compiler doesn't necessarily know what type of object is being passed in at compile-time. Suppose you have the following classes in a library:
public static class MessagePrinter
{
public static void PrintMessage(IMessage message)
{
Console.WriteLine(message.GetMessage());
}
}
public interface IMessage
{
public string GetMessage();
}
public class XMLMessage : IMessage
{
public string GetMessage()
{
return "This is an XML Message";
}
}
public class SOAPMessage : IMessage
{
public string GetMessage()
{
return "This is a SOAP Message";
}
}
At compile time, you don't know if the caller of that function is passing in an XMLMessage, a SOAPMessage, or possibly another type of IMessage defined elsewhere. When the PrintMessage() function is called, it determines which version of GetMessage() to use at runtime, based on the type of IMessage that is passed in.

Read : Polymorphism (C# Programming Guide)
Similar answer : Compile Time and run time Polymorphism
Well, there are two types of Polymorphism as stated below:
Static Polymorphism (Early binding)
Dynamic Polymorphism (Late binding)
Static Polymorphism(Early Binding):
Static Polymorphism is also know as Early Binding and Compile time Polymorphism. Method Overloading and Operator Overloading are examples of the same.
It is known as Early Binding because the compiler is aware of the functions with same name and also which overloaded function is tobe called is known at compile time.
For example:
public class Test
{
public Test()
{
}
public int add(int no1, int no2)
{
}
public int add(int no1, int no2, int no3)
{
}
}
class Program
{
static void Main(string[] args)
{
Test tst = new Test();
int sum = tst.add(10, 20);
// here in above statement compiler is aware at compile time that need to call function add(int no1, int no2), hence it is called early binding and it is fixed so called static binding.
}
}
Dynamic Polymorphism(Late Binding):
public class Animal
{
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
}
}
public class Dog:Animal
{
public override void MakeSound()
{
Console.WriteLine("Dog sound");
}
}
class Program
{
static void Main(string[] args)
{
Animal an = new Dog();
an.MakeSound();
Console.ReadLine();
}
}
As in the above code , as any other call to a virtual method, will be compiled to a callvirt IL instruction. This means that the actual method that gets called is determined at run-time (unless the JIT can optimize some special case), but the compiler checked that the method exists, it chose the most appropriate overload (if any) and it has the guarantee that the function pointer will exist at a well-defined location in the vtable of the type (even though that is an implementation detail). The process of resolving the virtual call is extremely fast (you only need to dereference a few pointers), so it doesn't make much of a difference.

public class Animal {
public virtual void MakeSound()
{
Console.WriteLine("Animal sound");
} }
public class Dog:Animal {
public override void MakeSound()
{
Console.WriteLine("Dog sound");
} }
class Program {
static void Main(string[] args)
{
Animal an = new Dog();
an.MakeSound();
Console.ReadLine();
} }
this is dynamic polymorphism,since it is decided at runtime which version of MakeSound will be called either of the parent or of the child, as a child may not override the parent function or may override it but all this is decided at runtime, which version is called ....

Related

Dynamic fails on private inner class

When I run the following code I get RuntimeBinderException: 'object' does not contain a definition for 'SetIt'.
public interface IInput { }
public interface IThing<in TInput>
{
void SetIt(TInput value);
}
public class ThingMaker
{
private class Thing<TInput> : IThing<TInput>
where TInput : IInput
{
public void SetIt(TInput value){}
}
private class Input : IInput {}
public IThing<IInput> GetThing()
{
return new Thing<IInput>();
}
public IInput GetInput()
{
return new Input();
}
}
class Program
{
static void Main(string[] args)
{
var thingMaker = new ThingMaker();
var input = thingMaker.GetInput();
dynamic thing= thingMaker.GetThing();
thing.SetIt(input);
}
}
If I switch thing to a var it works fine. So clearly, thing has SetIt. How come this fails when I use dynamic? Shouldn't any thing that works as var also work when it is dynamic?
I think it has something to do with Thing<TInput> being a private inner class because it works when I make it public.
Here is a simpler example of your problem:
class A
{
class B
{
public void M() { }
}
public static object GetB() { return new B(); }
}
class Program
{
static void Main(string[] args)
{
dynamic o = A.GetB();
o.M();
}
}
The generics and interfaces are just a distraction.
The problem is that the type B (or in your case, Thing<IInput>) is a private class, and so at the call site, cannot resolve to that actual type. Recall that dynamic simply is an object variable but where compilation has been postponed until run-time. It isn't intended to let you do things at run-time you wouldn't otherwise be able to do, and "wouldn't otherwise be able to do" is judged based on the accessible type at the call site (which in this case, is object).
As far as the runtime binder is concerned, the type is simply object (hence the error message telling you that object doesn't contain the member you want).
Of course, it is theoretically possible that dynamic could have been implemented differently, and could do a more in-depth search for valid types it could treat the object as for the purpose of binding members to the object (i.e. implemented interfaces rather than just the object's actual type). But that's just not how it was implemented, and it would have been much more costly to do so (both in terms of the original design and implementation, and of course in terms of run-time cost of code that uses dynamic).
Related reading (arguably duplicates):
Is this a bug in dynamic?
Is this a hole in dynamic binding in C# 4?

Using a generic parameter on overloaded methods

Why does this program output Generic Value and not Hello world!:
using System;
class Example
{
public static void Print<T>(T value)
{
Console.WriteLine("Generic Value");
}
public static void Print(string value)
{
Console.WriteLine(value);
}
public static void GenericFunc<T>(T value)
{
Print(value);
}
static void Main()
{
GenericFunc("Hello world!");
}
}
How is the generic method parameter being translated under the hood of C#?
Overload resolution is only done at compile-time.
Since GenericFunc<T> doesn't know whether T is a string or something else at compile-time, it can only ever use the Print<T>(T value) "overload".
Using dynamic, you can change this to a dynamic dispatch, and get the behaviour you expect:
Print((dynamic)value);
This makes the overload resolution happen at runtime, with the actual runtime type of value.
Simple answer to simple question
The other answer explains the way generic are bound (compile-time). But it doesn't answer on the OOP, good practice, or simply why you should never write this code in the first place.
OOP
The first O in OOP means Object and there is none with only static methods.
Responsibility
Let's think about the Generic versin of the method as a method responsible for printing a set of different possible types. String type is part of the set. So it should be managed by the generic version of your Print function.
public static void Print<T>(T value)
{
Console.WriteLine(value.ToString());
}
then you got the problem of nullity for ref types.
public static void Print<T>(T value) where T : class
{
if (value != null)
{
Console.WriteLine(value.ToString());
}
}
public static void GenericFunc<T>(T value) where T : class
{
Print(value);
}
And for those who are aware of why you should not use dynamic unless in some cases (see my anwer on that).
More clean OOP solution
Now imagine you have different objects to print. Each object should be responsible for knowing how to display it. Firstly, because it ease encapsulation of data by not leaking internal data to the external world. Secondly, because you've got an inherent coupling between the internal data and the printing function, so both should be located in the same place: inside the class. That's the purpose of the ToString function.
Let's take some height...
Now, we could imagine that it's not a Print function but something else.
We got a hierarchy of classes with overload on the same function (let's call it Foo) and a collection of instances from these classes for which you must call the function Foo. Let's then make all these classes implement the IFooCallable interface :
public interface IFooCallable
{
void Foo();
}
A little more complex...
Ok, but imagine that there is not common way to process all these instances of classes because there are very different.
Let's call the Visitor pattern. It's commonly used when you want to analyze some object tree with each node very different (like in AST).
It's a known pattern, making it easy to share knowledgable information with your team.
You got the Visitor:
public class Visitor : IVisitor
{
public void Visit(Foo foo)
{
// do something with foo
}
public void Visit(Bar bar)
{
// do something with bar
}
}
and the Visitable
public class Foo : IVisitable
{
public void Accept(IVisitor visitor)
{
visitor.Visit(this);
}
}
Moreover this pattern is reusable (you could write several implementation of IVisitor should you need to).
I don't buy the dynamic thing. Especially when there is more cleaner, faster alternative. If dynamic so great, why not writing this then ;)
public static void Print(dynamic value)
{
Console.WriteLine(value);
}
public static void GenericFunc(dynamic value)
{
Print(value);
}
static void Main(dynamic[] args)
{
GenericFunc((dynamic)"Hello World");
}

MyClass equivalent in C#

In looking at this question, commenter #Jon Egerton mentioned that MyClass was a keyword in VB.Net. Having never used it, I went and found the documentation on it:
The MyClass keyword behaves like an object variable referring to the current instance of a class as originally implemented. MyClass is similar to Me, but all method calls on it are treated as if the method were NotOverridable.
I can see how that could kind of be useful, in some specific scenarios. What I can't think of is, how would you obtain the same behaviour in C# - that is, to ensure that a call to a virtual method myMethod is actually invoked against myMethod in the current class, and not a derived myMethod (a.k.a in the IL, invoking call rather than callvirt)?
I might just be having a complete mental blank moment though.
According to Jon Skeet, there is no such equivalent:
No, C# doesn't have an equivalent of VB.NET's MyClass keyword. If you want to guarantee not to call an overridden version of a method, you need to make it non-virtual in the first place.
An obvious workaround would be this:
public virtual void MyMethod()
{
MyLocalMethod();
}
private void MyLocalMethod()
{
...
}
Then you could call MyLocalMethod() when a VB user would write MyClass.MyMethod().
There is no C# equivalent of the MyClass keyword in VB.Net. To guarantee that an overridden version of a method will not be called, simply make it non-virtual.
In addition to answers saying it doesn't exist, so you have to make it non-virtual.
Here's a smelly (read: don't do this!) work-around. But seriously, re-think your design.
Basically move any method that must have the base one called into 'super'-base class, which sits above your existing base class. In your existing class call base.Method() to always call the non-overridden one.
void Main()
{
DerivedClass Instance = new DerivedClass();
Instance.MethodCaller();
}
class InternalBaseClass
{
public InternalBaseClass()
{
}
public virtual void Method()
{
Console.WriteLine("BASE METHOD");
}
}
class BaseClass : InternalBaseClass
{
public BaseClass()
{
}
public void MethodCaller()
{
base.Method();
}
}
class DerivedClass : BaseClass
{
public DerivedClass()
{
}
public override void Method()
{
Console.WriteLine("DERIVED METHOD");
}
}

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

Generic extension methods in C#: what will happen in this edge case?

In a recent question of mine I learned that if there are more than one extension methods with constraints that match the given type, the most specific one will be chosen. This got me thinking - how does the compiler determine which one is "more specific"? And what will the outcome be?
Let's say I have the following classes:
public MyClass : IComparable, IDisposable
{
// Implementation of members
}
public static class MyExtensions
{
public static void DoSomething<T>(this T item)
where T : IComparable
{ /* whatever */ }
public static void DoSomething<T>(this T item)
where T : IDisposable
{ /* whatever else */ }
}
If I now use the extension method as
var instance = new MyClass();
instance.DoSomething();
which method will be used? Or will the compiler throw an error?
Note: I'm not saying this is good design, or even that I have a case where I need to do this. But the term "more specific" was loose enough to make me ponder this, and now I have to know! :P
Update:
I guess I wasn't really as interested in what will happen in the above example, as in why. It came to my mind since I'd been doing stuff like
public static class CollectionExtensions
{
public static void DoSomething<T>(this T items) where T : IList { ... }
public static void DoSomething<T>(this T items) where T : IEnumerable { ... }
}
where the compiler knows to choose the first method for new List<Something>().DoSomething(), since it is "closer" to the type passed. What I was interested in then, was "what does closer in this context mean? How will the compiler react if the constraints are from two different inheritance chains? Why?"
The extensions class won't compile, in this case - you can't overload methods based solely on generic constraints.
If you put the two extension methods into different classes, then the calling code wouldn't compile - it would be an ambiguous call, as neither method would be "better" than the other... in both cases the generic type argument would be inferred as MyClass, so there'd just be two conversions from MyClass to MyClass, neither of which is better than the other.
This is basically just a special case of overloading, once you've found out that no instance methods are applicable. I wrote an article on overloading just recently which you may find useful - it doesn't call out this specific case, but it points to the relevant bits of the spec if you want to look in detail.
It will not compile at all and throw a compile time error saying call is ambiguish between the two methods.
Type 'MyExtensions' already defines a
member called 'DoSomething' with the
same parameter types.
EDIT
Here's why compiler gives such error. Extension methods are just syntactic sugars and all they do is bring fluency and readabilty on any type.
Check this code..
var instance = new MyClass();
instance.DoSomething();
Compiler replaces this code as following.
var instance = new MyClass();
MyExtensions.DoSomething(instance);
//Compiler gets confused. Which one to call IComparable or IDisposable
In your case compiler gets confused since there are two matching signatures to the method-call and it gives you the said error.
Generic constraints are not considered as part of method signature. These two methods are considered by compiler as ones with the same signature. So you will get compile error saying that method DoSomething is already defined.
public static void DoSomething<T>(this T item)
where T : IComparable
{ /* whatever */ }
public static void DoSomething<T>(this T item)
where T : IDisposable
{ /* whatever else */ }
Consider the following example:
class MyClass {}
static class MyClassExtensions
{
public static void DoSomething<T>(this T item, List<string> someList)
{
Console.WriteLine("Method with List in signature is called.");
}
public static void DoSomething<T>(this T item, IEnumerable<string> someEnumerable)
{
Console.WriteLine("Method with IEnumerable in signature is called.");
}
}
In this example, when testing with the following:
var myClass = new MyClass();
myClass.DoSomething(new List<string>());
The first method in the extensions class is called. In short, this means that the compiler determines the signature that is nearer the arguments passed, and employs that.

Categories

Resources