Home > DeveloperSection > Interviews > What is the overriding and overloading in C# with example?

Posted on    September-17-2016 7:49 AM

 C# C# 
Ratings:
 1 Answer(s)
  82  View(s)
Rate this:

Abhishek Srivasatava
Abhishek Srivasatava

Total Post:70

Points:350
Posted on    September-17-2016 7:49 AM

What is the overriding and overloading in C# with example?

Overloading: This concept is useful when we need the function / method of the same name but different signature or parameter or type. It is the example of compile time polymorphism. 

Example

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace ConsoleApplication15
{
    public class program1
    {
        public int add(int a, int b) 
        {
            return a + b;
 
        }
        public int add(int a, int b, int c) 
        {
            return a + b + c;
 
        }
 
       }
    }   
    class Program
    {
        static void Main(string[] args)
        {      program1 p1 = new program1();
      int b = p1.add(2, 3);
      int c = p1.add(2, 3,4);
      Console.WriteLine("{0}{1}",b,c);           Console.ReadLine();
        }
    }
}

Overriding: Concept for the overriding is useful when we need a method / function of the same name, parameter, type and the signature which is defined in base and derived class. The advantage of this is that memory will allocate only for one method/function. It is the example of Dynamic time polymorphism. 

It can be done by using the keyword Virtual (before the function name define in base class) and override (before the function name define in derived class)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApplication15
{
    public class program1
    {
       
    public virtual int fun() 
    { 
        return 55;      } 
  } 
public class program2 :program1

    
    public override int fun() 
    { 
        return 90;      }
    } 
    class Program
    {
        static void Main(string[] args)
        {
                       
            program1 p1 = new program1();
            program2 p2 = new program2();
 
           int  b= p1.fun();
           
            int c = p2.fun();
          Console.WriteLine("{0}\n{1}",b,c);
            Console.ReadLine();
 
        }
    }
}
 
 

Modified On Sep-25-2016 11:43:12 PM

Don't want to miss updates? Please click the below button!

Follow MindStick