A word of caution while Overloading Methods in C#

  

While working with Method Overloading, there are some corner cases which we should be careful about. So we know overloading is possible when parameter type and parameter order. But there is a lot which also depends on what parameter values are you using.

For instance

         public void Foo(int x, float y) 
        {
            // Do something useful            
        }

        public void Foo(float a, int b) 
        {
            // Do something useful here too            
        }

 

In this scenario, weather the code compiles well or not depends on what parameter values are you going to pass.

 This will work - 
 obj.Foo(10, 10.00f);

This will result in compile time error

 obj.Foo(10, 20);

image

So the bottom line is: while overloading Methods (or anything else for that matters), one need to ensure that at all time, it should be absolutely clear to compiler that which method needs to be called. There should be exactly one match at all the time. Such scenarios are especially of importance when your class is supposed to be used by other (probably external) classes where you may not discover the ambiguity until late.

There are lot of such combinations like – Foo(int x, int y) & Foo(double a, double b) etc.

More on this is discussed in C# In-Depth

Cheers!