For purposes of automatically translating code from C++ to C#, I would like to have a C# class (psuedo-code)
class Null {
public static implicit operator T (Null unused) {
return null;
}
}
This would be useful in cases such as
foo(T1 x) { ... }
foo(T2 x) { ... }
foo(null); // ambiguous
For certain reasons, programmatically disambiguating the above type is not in general possible. E.g.
foo((T1)null); // Discovering T1 over T2 is not possible or really hard to do
But if I had the Null
class above, I could programmatically add in
foo(Null x) {...}
and generate
foo(new Null()); // not ambiguous
The trick would be to use new Null()
in place of every generated null
such that even
T1 x = new Null();
compiles with x == null
.
Is it possible to write such a class?
No. Absent the dynamic
keyword, all method binding in C# is done at compile-time--even binding to implicit cast operators. That means that the problem you're running into with method overload resolution will also prevent the compiler from being able to figure out whether you want your null
to be implicitly cast to a T1 or a T2. And using dynamic
won't work, because null
doesn't have any type at runtime.
It is possible that there are other solutions to your problem if you can share more information. For example, if either of the two methods would work correctly when passed a null value, and you're just trying to get the generated code to compile, you could create a method like this:
foo(object o) {return Foo((T1)null);}
And then translate calls to:
foo(new object());
The above method would also work if you wanted to use a Null
class instead of object
--no implicit cast is necessary.
On the other hand, if it does matter which overload gets called with a null value, then you need to tell us how the original program determines which one to call.