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;
}
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
user3573341
  • 391
  • 3
  • 8

3 Answers3

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.

Community
  • 1
  • 1
Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
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)

Anton Kedrov
  • 1,767
  • 2
  • 13
  • 20
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.

Dmitry Egorov
  • 9,542
  • 3
  • 22
  • 40