Method Signatures in C#

Methods, constructors, indexers, and operators are characterized by their signatures. A signature makes a method look unique to the C# compiler. The method name and the type and order of parameters all contribute to the uniqueness of signatures.

Signatures enable the overloading mechanism of members in classes, structs, and interfaces.

A method signature consists of the name of the method and the type and kind, such as value or reference. A method signature does not include the return type, nor does it include the params modifier that may be specified for the last parameter.

A constructor signature consists of the type and kind, such as value or reference. A constructor signature does not include the params modifier that may be specified for the last parameter.

An indexer signature consists of the type. An indexer signature does not include the element type.

An operator signature consists of the name of the operator and the type. An operator signature does not include the result type.

Listing 5.77 illustrates the signature concept.

Listing 5.77: Signatures Example class

void MyFunc(); // MyFunc ()
void MyFunc(int x); // MyFunc (int)
void MyFunc(ref int x); // MyFunc (ref int)
void MyFunc(out int x); // MyFunc (out int)
void MyFunc(int x, int y); // MyFunc (int, int)
int MyFunc(string s); // MyFunc (string)
int MyFunc(int x); // MyFunc (int)
void MyFunc(string[] a); // MyFunc (string[])
void MyFunc(params string[] a); // MyFunc (string[])

The ref and out parameter modifiers are part of a signature. MyFunc(int), MyFunc(ref int), and MyFunc(out int) are all unique signatures. The return type and the params modifier are not part of a signature, and it is not possible to overload based solely on return type or on the inclusion or exclusion of the params modifier.

Notice that there are some errors for the methods that contain duplicate signatures like MyFunc(int) and MyFunc(string[]) whose multiple signatures differ only by return type.

Conclusion

Hope this article would have helped you in understanding Method Signatures in C#. See other articles on the website on .NET and C#.