The following does not compile:
public struct Foo
{
public static implicit operator Foo(string bar)
{
return new Foo();
}
public static implicit operator Foo(long? bar)
{
return new Foo();
}
public static void Test()
{
Foo bar = 0;
Foo bar2 = (long?)null;
Foo bar3 = "";
Foo bar4 = null; // Cannot convert null to 'Foo' because it is a non-nullable value type
}
}
'Foo bar4 = null' fails, presumably because the compiler doesn't know which implicit operator to use, because changing the operator from long? to long causes that line to compile but instead 'Foo bar2 = (long?)null' fails instead (requiring an explicit cast).
My question is; Is there a way to make 'Foo bar4 = null' work as well, or is this just a limitation of the language (that I cannot add a 'null' operator or tell it which one to use for null for instance)?
I realize I could change the struct to a class, but I don't want it to be null, I want to be able to have null create an instance of it.
EDIT: I should add that I understand there are a lot of ways to get around this, but since '= null' (doing 'new Foo()' essentially) works with only one of the implicit operators, I'm just wondering if it's possible to have it still work with both of them there (I feel like there should be a way in the language to do this - either now or in the future, no?).