views:

62

answers:

5

Compiling the following code will return The call is ambiguous between the following methods or properties error. How to resolve it since I can't explicitly convert null to any of those classes?

static void Main(string[] args)
{
    Func(null);
}

void Func(Class1 a)
{

}

void Func(Class2 b)
{

}
+4  A: 

Cast null to the type:

Func((Class1)null);
Pieter
+6  A: 
Func((Class1)null);
moi_meme
+2  A: 

You should be able to cast null to either of those, the same as you would a variable Func((Class1)null).

Dave
+2  A: 

You could also use a variable:

Class1 x = null;
Func(x);
Dismissile
+1 This method is easier to read and understand than func((Class1)null). Casting null is not intuitive.
wllmsaccnt
+3  A: 

The Func() methods accept a reference type as a parameter, which can be null. Since you're calling the method with an explicit null value, the compiler doesn't know whether your null is supposed to be in reference to a Class1 object or a Class2 object.

You have two options:

Cast the null to either the Class1 or Class2 type, as in Func((Class1)null) or Func((Class2)null)

Provide a new overload of the Func() method that accepts no parameters, and call that overload when you don't have an explicit object reference:

void Func()
{
    // call this when no object is available
}
JeffFerguson