Saturday, August 22, 2015

Ambiguous Invocation from Optional Parameter Overloads

There are many reasons for your C# compiler to give you an ambiguous invocation error. When using optional arguments you have to be sure not to create an overload that have overlapping optional parameters. Let's take a look:

public void DoStuff(int i, object o = null) { }
 
public void DoStuff(int i, string s = null) { }
 
public void DoStuff(int i, string s = null, bool b = false) { }
 
public void Test()
{
    // Ambiguous invocation!
    DoStuff(1);
}

There is no need to create methods like the ones shown above!

Instead consider that there is no reason to have two overloads being called with the potentially the same parameters. Such overloads should be combine into one method, and other overloads with different types argument can just be written as normal parameters without default values. Again, let's take a look:

public void DoStuff(int i, object o) { }
 
public void DoStuff(int i, string s = null, bool b = false) { }
 
public void Test()
{
    // No more ambiguous invocation :)
    DoStuff(1);
}

I hope that helps,
Tom

2 comments:

  1. Quadrobits gives a holistic virtual marketing answer, overlaying internet site optimization, search engine optimization, % ads, content marketing, social media control, e-mail campaigns, analytics, and on-line reputation control. More info here quadrobits.

    ReplyDelete
  2. Play the most exciting online slots at Slotbaru! Featuring high RTP games, huge jackpots, and a 100% slot bonus, this is the best site for winning big. Deposit just 10K via BCA, OVO, or Sakuku and start playing immediately. Take advantage of exclusive promotions and jackpot events at slotbaru today!


    ReplyDelete

Real Time Web Analytics