.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
 
Sign In
Register
 
Win Surprise Gifts!!!
Congratulations!!!


Top 5 Contributors of the Month
david stephan

Home >> Articles >> C# >> Post New Resource Bookmark and Share   

 Subscribe to Articles

Betterness rule while calling a method in C# 4.0

Posted By:shankey       Posted Date: January 28, 2011    Points: 75    Category: C#    URL: http://www.dotnetspark.com  

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

 Subscribe to Articles

     

Further Readings:

Responses

No response found. Be the first to respond this post

Post Comment

You must Sign In To post reply
Find More Articles on C#, ASP.Net, Vb.Net, SQL Server and more Here

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend