2

why overloading like this is working in c#?

public string DisplayOverload(string a, string b, string c = "c") { return a + b + c; } public string DisplayOverload(string a, string b, out string c) { c = a + b; return a + b; } 

while this is not working

public string DisplayOverload(string a, string b, string c = "c") { return a + b + c; } public string DisplayOverload(string a, string b, string c) { return a + b + c; } 
3
  • method overloading is based on number of arguments and type of arguments Commented May 29, 2015 at 10:33
  • The last 2 are the same signature. The first 2 are different because one has an out parameter. Commented May 29, 2015 at 10:37
  • The first may "work", but it's still a code smell. The do different things, so give them different names. Commented May 29, 2015 at 10:39

3 Answers 3

3

out and ref are considered part of the method signature.

From $3.6 Signatures and overloading;

Note that any ref and out parameter modifiers (Section 10.5.1) are part of a signature. Thus, F(int) and F(ref int) are unique signatures.

Your second example, c is optional argument. Even if you call without this parameter value, 3 parameter overloaded method called but compiler can't know that which one to call.

For more information, check Eric Lippert's answer about this topic.

Sign up to request clarification or add additional context in comments.

Comments

0

Method with output parameter will have different signature, while method with optional parameter may have the same signature.

Works fine

DisplayOverload(string a, string b, string c)

DisplayOverload(string a, string b, out string c)

Will not work, since signature is the same

DisplayOverload(string a, string b, string c) - optional c is always set either default or other value

DisplayOverload(string a, string b, string c)

Comments

0

Because with the second pair of definitions the compiler wouldn't be able to tell DisplayOverload("aa", "bb", "cc") (when you mean it for the first function) from DisplayOverload("aa", "bb", "cc") (when you mean it for the sencond one).

On the other hand it's quite easy for the compiler to distinguish string c; DisplayOverload("aa", "bb", c) and string c; DisplayOverload("aa", "bb", out c). Notice the out in the last call.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.