C# documentation Methods states
Methods are declared in a class, struct, or interface 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.
public class Foo
{
public int InstanceMethod1()
{
return 85;
}
public static string StaticMethod1()
{
return "Bar";
}
}
In regards to the above excerpt, by "return value" is it referring to the "return type" of the method? Thus, the return type of a method (in the above examples int
and string
) is considered part of the signature of the method?
Note, I did read following side note "A return type of a method is not part of the signature of the method for the purposes of method overloading. However, it is part of the signature of the method when determining the compatibility between a delegate and the method that it points to."... However, my above example has nothing to do with method overloading.
The return value of a method must strictly follow the return type of its method so you could technically use the two terms interchangeably when talking about method signatures which it looks like they've done in the excerpt, albeit confusing.
In the case of method overloading the return type is not considered part of the method signature as the compiler cannot determine on return type alone which methods to use and as such the return type is not included in the method signature. For example consider the following overloaded methods where only the return type differs:
public int GetResult() { }
public double GetResult() { }
If we were to call this method, how would the compiler know which method to use?
var result = GetResult();
However as the language definition states: the method name, number of generic types, number of and type of each formal parameter and out/ref/value parameters are part of the method signature when overloading so for example if you wanted to overload then you could do:
public int GetResult() { }
public int GetResult(int x) { }
There are cases where the return type of a method is considered part of the signature such as delegates since the method must have the same return type as the delegate declaration. As per the C# specification:
In the context of method overloading, the signature of a method does not include the return value. But in the context of delegates, the signature does include the return value. In other words, a method must have the same return type as the delegate.