How to resolve ambiguity when argument is null?
Asked Answered
B

7

26

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)
{

}
Bloodfin answered 28/10, 2010 at 14:52 Comment(1)
oh, sorry, looks like I can :)Bloodfin
F
39
Func((Class1)null);
Fley answered 28/10, 2010 at 14:55 Comment(0)
K
12

You could also use a variable:

Class1 x = null;
Func(x);
Kab answered 28/10, 2010 at 15:0 Comment(2)
+1 This method is easier to read and understand than func((Class1)null). Casting null is not intuitive.Gearalt
This is preferable to casting wherever possible, as it catches many problems at compile time that would otherwise be runtime cast errors.Arrowhead
N
11

Cast null to the type:

Func((Class1)null);
Nubble answered 28/10, 2010 at 14:54 Comment(0)
L
11

Using as for the casting makes it slightly more readable with the same functionality.

Func(null as Class1);
Laity answered 26/7, 2011 at 20:30 Comment(0)
C
4

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
}
Cincinnati answered 28/10, 2010 at 15:1 Comment(0)
L
3

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

Legislatorial answered 28/10, 2010 at 14:55 Comment(0)
A
0

Just an alternative solution I prefer

static void Main(string[] args)
{
    Func(Class1.NULL);
}

void Func(Class1 a)
{ }

void Func(Class2 b)
{ }

class Class1
{
    public static readonly Class1 NULL = null;
}

class Class2
{
    public static readonly Class2 NULL = null;
}
Adnopoz answered 20/10, 2018 at 12:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.