NET and Programming C#: overloading methods by return type is not permitted...

but only because the language is a CLS compatible language.
In C#, a type have several many methods with the same name provided they have different set of parameters. This feature is called overloading. The C# standard bases its overload concept on the notion of signature. In C#, the signature of a method is formed by its name and its parameter set. Notice that the return type of a method isn't included on its signature! The following list exemplifies this concept:
void Method();
void Method(int a); //ok: different parameter set
void Method(string a, int b);//ok again
void Method(string h, int t);//error same parameter set as previous method
int Method(int g); //error: can't overload based on return type only
As you can see, even though the last method has a different return type from the second one, it still causes a compile time error which says that there's already a member with that signature.
Generally, the concept of overload is easy to grasp if you get the concept of signature (which isn't really that hard). I'm only writing about this because most people think that the signature concept is imposed by the CLR and this is not correct. For instance, if you look at point 8.6.1.5 of partition I of the CLI, you'll see that it defines the signature of the method as being composed of:
  • calling convention;
  • number of generic parameters (if the method is generic);
  • List of zero or more parameter signatures;
  • type signature for return result .
As you can see, the return result signature is included in the signature of the method. If you follow my advice (and read Richter's excellent book) you'll see that, currently, the only language which will let you overload a method based on its return type is IL (and no, this is not something you would want to do).
btw,if you're really into specs, you should search for CLS rule 38, which specifies the necessary conditions for overloading support in a CLS language.

0 comments:

Post a Comment