Jul 20, 2015

Method with same name and signature but return type in C#

yes you can use the same method, same parameters (need to customize) and different return values.
Just follow the codes below, it might help you.
public class myClass
{
    public int myReturn() { return 123; }
    public string myReturn(string temp = null) { return "test"; }
}
the thing is, it requires parameter to make execute the functions, but you still able to ignore the parameters since you have string temp = null as optional parameters, which is you still call the functions with or without the parameters.
 
 
Can we declare 2 methods with same parameters and different return types?
Answer

No,it is not possible, It give error like “method Add is defined with same parameter types”. You can try with below code.

public int Add(int Number1, int Number2)

{

return (Number1 + Number2);

}





public float Add(int Number1, int Number2)

{

return (Number1 + Number2);

}

Method overloading method have same name but their parameter list should be different in term of parameters or their data type. So if Method return type different then it not call method overloading.

No comments:

Post a Comment