0

I was enhancing a set of methods this afternoon after finally migrating out of .Net 3.5, and wanted to add optional parameters to a method and it's overload. I found that I was able to compile a method and its overload when they could have an ambiguous meaning. A sample below (tested in MonoDevelop, I don't have access to my windows box at the moment that I found it on).

class MainClass
{
    public static void DoSomething(DateTime? one = null){
        Console.WriteLine("DoSomething: " + one);
    }

    public static void DoSomething(DateTime? one, DateTime? two = null){
        Console.WriteLine("DoSomethingElse: " + one + " " + two);
    }

    public static void Main (string[] args)
    {
        DoSomething ();
        DoSomething (DateTime.MinValue);//What if I want to DoSomethingElse?
        DoSomething (DateTime.MinValue, DateTime.MaxValue);
        Console.ReadKey ();
    }
}

Output:

DoSomething: 
DoSomething: 1/1/0001 12:00:00 AM
DoSomethingElse: 1/1/0001 12:00:00 AM 12/31/9999 11:59:59 PM

I understand that I can just call the first method with a named parameter DoSomething(one:DatTime.MinValue) but I would think that the above snipped shouldn't compile.

Any ideas why this is a valid use case of the language?

Chris
  • 4,425
  • 5
  • 34
  • 49
  • 3
    Related: http://stackoverflow.com/questions/2674417/conflicting-overloaded-methods-with-optional-parameters – shree.pat18 Nov 24 '15 at 01:45
  • It doesn't seem to be too odd an issue. You are calling `DoSomething ` with a single `DateTime?` and there is a specific overload that matches that signature exactly. The other overload is not an exact match, so it's not chosen. The compiler always chooses exact matches over fuzzy ones. – Enigmativity Nov 24 '15 at 03:40
  • Yep that makes sense I think, but I am curious why the language allows the "fuzzy ambiguity" at all I guess. – Chris Nov 24 '15 at 04:14
  • In Visual Studio + ReSharper you get a warning: "method with optional parameter is hidden by overload". Not sure if you could make the compiler throw an actual warning though. Maybe with a custom filter in Roslyn. – Greg Nov 24 '15 at 13:14

0 Answers0