Betterness rule while calling a method in C# 4.0


In a case where a method is overloaded and along with that some of the parameters are optional for one or more definitions, then there is some confusion related to which version of the overloaded method is to be called.

To understand in which case betterness rule applies. Let us have a look at the following example:

1. BestMatch

public static void BestMatch(String str)
{
    Console.WriteLine("called  public static void BestMatch(String str)");
}

2. BestMatch

        public static void BestMatch(Object obj)
        {
            Console.WriteLine("called public static void BestMatch(Object obj)");
        }

3. BestMatch

        public static void BestMatch(String str,Int16 iint=4)
        {
          
Console.WriteLine("calledpublic static void BestMatch(String str,Int16 iint=4)");
        }

4. BestMatch

        public static void BestMatch(Int16 iint,String str="WWW")
        {
            Console.WriteLine("called   public static void BestMatch(Int16 iint,String str="WWW")");
        }

Above are some definition (overloaded) of the BestMatch method.

When a call to BestMatch method is made using following statement:

   BestMatch("WWW");

Guess which overloaded version of the method is called.

First of all the following method is not applicable

because it is not possible to convert String to Int16.

public static void BestMatch(Int16 iint,String str="WWW")

Secondly the following method is overlooked

public static void BestMatch(Object obj)

because the following method is much better.

Lastly the following method is also overlooked

public static void BestMatch(String str,Int16 iint=4)

Because the calling statement omits the optional parameter.

Finally when the following method is called

public static void BestMatch(String str)

The following is the output:

out.gif

Up Next
    Ebook Download
    View all
    Learn
    View all