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

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 exa:
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 = an.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.

Comments