Now we will consider cases on which function overloading depends on:-
- Variable Number of parameters to function
public class MyBaseClass
{
public void foo()
{
Console.WriteLine("Hi I am original");
}
public void foo(int i)
{
Console.WriteLine("Hi I am overloaded and
here is the value of i " + i.ToString());
}
}
In this example, number of parameters are different so this will compile fine and now when you create object of this class you will see two overloaded version of foo.
Let’s now create object of this class and call both the versions:-
MyBaseClass obj = new MyBaseClass();
obj.foo();
obj.foo(10);
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
Here is the output:-
Hi I am original
Hi I am overloaded and here is the value of i 10
4. Order of parameters to function
public class MyBaseClass
{
public void foo(int i, string s)
{
Console.WriteLine("The parameter order is int and string.
The value of i is {0} and that of s is {1}", i, s);
}
public void foo(string s, int i)
{
Console.WriteLine("The parameter order is string and int.
The value of i is {0} and that of s is {1}", i, s);
}
}
In the example above, number of parameters is same but since the order is different so this will compile fine.
Let’s now create object of this class and call both the versions:-
MyBaseClass obj = new MyBaseClass();
obj.foo(1,”shakti”);
obj.foo(“Test”,2);
Here is the output:-
The parameter order is int and string.The value of i is 1 and that of s is shakti
The parameter order is string and int.The value of i is 2 and that of s is Test
style="display:block; text-align:center;"
data-ad-format="fluid"
data-ad-layout="in-article"
data-ad-client="ca-pub-5021110436373536"
data-ad-slot="9215486331">
5. Data type of parameters
public class MyBaseClass
{
public void foo(int i)
{
Console.WriteLine("The is one parameter function which takes int as
parameter and value of i is {0}.", i);
}
public void foo(string s)
{
Console.WriteLine("The is one parameter function which takes string as
parameter and value of s is {0}.", s);
}
}
Here the number of parameters is same but data types are different so this will compile fine.
Let’s now create object of this class and call both the versions:-
MyBaseClass obj = new MyBaseClass();
obj.foo(10);
obj.foo(“Test”);
Output:-
The is one parameter function which takes int as parameter and value of i is 10.
The is one parameter function which takes string as parameter and value of s is Test.