0
Define the method overloading and overriding in c# also differentiate between them?
Define the method overloading and overriding in c# also differentiate between them?
Syntax
[datatype] method-name(datatype arguments){
Statement;
}
[datatype] method-name(datatype arguments, datatype arguments){
Statement;
}
Syntax
[datatype] method-name(datatype arguments){
Statement-1;
}
[datatype] method-name(datatype arguments){
Statement-2;
}
| Overloading | Overriding |
| its define in the same class | its define in child class |
| its depend on a parameter but function name are same | function name and arguments are the same but the internal statement is change |
| It applies to compile time | It applies to the run time |
using System;
class Demo {
public void PrintPattern(int length){
for(int i=1; i<=length;i++)
Console.Write('{0}{1}',i,i < length ? ',':'');
Console.WriteLine();
}
// overload the PrintPattern method 2 parameter
public void PrintPattern(int length, char ch){
for(int i=1; i<=length;i++)
Console.Write('{0}{1}',ch,i < length ? ',':'');
Console.WriteLine();
}
// overload the PrintPattern method with 3 parameter
public void PrintPattern(int length, char ch, string seperator){
for(int i=1; i<=length;i++)
Console.Write('{0}{1}',ch,i < length ? seperator:'');
Console.WriteLine();
}
// making SayHello function for override
public virtual void SayHello(){
Console.WriteLine('Say Hello in Parent Class');
}
}
class Demo2 : Demo
{
// override sayhello method from parent class
public override void SayHello(){
Console.WriteLine('Say Hello in child Class');
}
}
public class Program
{
public static void Main()
{
Demo dm=new Demo();
dm.PrintPattern(10);
dm.PrintPattern(10,'*');
dm.PrintPattern(10,'*','!');
dm.SayHello();
Demo dm2=new Demo2();
dm2.SayHello();
}
}
Output
1,2,3,4,5,6,7,8,9,10
*,*,*,*,*,*,*,*,*,*
*!*!*!*!*!*!*!*!*!*
Say Hello in Parent Class
Say Hello in child Class