Reputation: 8499
Can I have two same function name with same parameters but different meaning.
For example:
public void test(string name)
public void test(string age)
Thank you.
Upvotes: 5
Views: 245
Reputation: 155
NO.
An OVERLOADED FUNCTION must have different SIGNATURE. i.e.- arguments should be different, either in terms of number of arguments or order of different datatypes arguments.
Upvotes: 0
Reputation:
No - the compiler throws an error because compiler use parameters to detemine which method to call, not the return type.
Upvotes: 0
Reputation: 15578
No, you can't. The signature is not different - it doesn't matter what the parameter names are.
Methods are declared in a class or struct by specifying the access level such as public or private, optional modifiers such as abstract or sealed, the return value, the name of the method, and any method parameters. These parts together are the signature of the method.
Like a few other answers have stated, consider the type of data you're taking in. Name is indeed a typical string, but does age have to be? If you allow it to be a - for example - int
then you can overload your method as you wish.
Upvotes: 4
Reputation: 3761
You could mix together these methods using optional parameters and default values:
public void test(string name = null, string age = null)
{
if (name != null)
{
// Do something
}
else if (age != null)
{
// Do something else
}
}
And you could call this method like that:
test(name: "John");
test(age: "30");
Not very clean, but still useable.
Upvotes: 1
Reputation: 68566
You can have static and non-static methods with the same name, but different parameters following the same rules as method overloading, they just can't have exactly the same signature.
Upvotes: 2
Reputation: 726479
No, you cannot overload on a return type or a parameter name. Unlike some other languages (most notably, Objective C1) parameter name is not part of the signature of your function.
The signature of a method consists of the name of the method and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. The signature of a method specifically does not include the return type, nor does it include the params modifier that may be specified for the right-most parameter.
Upvotes: 3
Reputation: 9030
No. Signatures and Overloading
If you need a method with different meaning why won't you create a method with a different name? It would be confusing to use the same method name for different things on the same object.
Upvotes: 1