Sep 22

Back to methods: overloading

Posted in Basics C#      Comments Off on Back to methods: overloading

After a small JavaScript detour, I’m back into .NET land. We’ve already seen several interesting details regarding methods, but we still haven’t really discussed the concept of overloading. So, what’s method overloading? The concept is simple, but before, we should probably find a good enough definition for a method. For now, lets define a method as a name that represents a piece of code which performs some operation on a type or on an instance of a type.

If you’ve been doing C# for some type, then you know that you can have several methods with the same name, provided they have a different set of arguments. Ok, here’s a small sample which shows the concept:

public class Student {
    //static overloads
    public static void SayHi(Student std) {
    public static void SayHi(Student std, String msg){
    //instance overloads
    public void SayHi() {
    public void SayHi(String msg) {

The previous snippet shows how you can overload static and instance methods. In C#, you can only overload based on a different set of parameters. That means you cannot add the following method to the Student type without getting a compilation error:

//can't overload based on return type
public String SayHi(String msg) {

Now,do keep in mind that the CLR does allow this kind of stuff,ie, it does allow you to overload with a different return type. Anyway, we’re writing C# code, so to achieve that, we really need to write IL (which is not going to happen right now, so we’ll consider this paragraph a small side note:)).

Ok, back to C#…so why doesn’t C# allow overloads based in the return type? That happens because overloading is based on having different method signatures. In C#, a method signature consists of its name, the number of type parameters and the type and kind of each of its parameters (considered from left to right). Besides the return type, in C# the params keyword and the type parameter constraint (when you’re using generics) aren’t part of the method signature. Another interesting gotcha is that you cannot override solely based in the out/ref modifiers (as we’ve seen that in the past). Interestingly, the our/ref keywords are considered part of the signature for hiding/overriding purposes.

Overload resolution is an important concept which is used to decide which method will be called when you” write code like the following:

var std = new Student();

The algorithm for finding a method involves several steps. Instead of describing the complete process here (which would involve some serious copying of the C# spec) and since  this is becoming a large post, I guess I’ll just redirect you to the C# spec for getting the complete story on method overload resolution. So, open your C# spec and read the section carefully to see what I mean…And that’s it for now. Tomorrow, we’ll continue our basic tour around .NET and the CLR. Stay tuned for more.