Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to allow a generic type parameter for a C# method to accept a null argument?

private static Matcher<T> EqualTo<T>(T item)
{
    return new IsEqual<T>(item);
}

How do I modify the above method definition such that the following are valid/allowed.

EqualTo("abc");
EqualTo(4);
EqualTo(null); // doesn't compile. EqualTo<string>(null) does

Trying to port some Java code where null seems to be acceptable value for a T parameter.


Update
Thanks: for all the answers - especially Eamon and Jason. I didn't want the method calls to bother with type-inference. The following overload fixed it.

    private static Matcher<object> EqualTo(object item)
    {
        return EqualTo<object>(item);
    }  

Actually the above question was a part of a larger puzzle. The end goal was for the following to work.

        this.AssertThat(null, EqualTo(null));
        this.AssertThat(null, Not(EqualTo("hi")));
        this.AssertThat("hi", Not(EqualTo(null)));

Applied the same fix.. RFC. (Ignore the ugly extension method part - that's another problem. Wanted to have these methods in all test-fixtures without inheritance.)

public static void AssertThat<T>(this object testFixture, object actual, Matcher<T> matcher, string message = "")
{
  AssertThat(anyObject, (T)actual, matcher, message);
}

public static void AssertThat<T, TSuper>(this object testFixture, T actual, Matcher<TSuper> matcher, string message = "") where T : TSuper
{
  ... check and assert
like image 750
Gishu Avatar asked Apr 10 '11 14:04

Gishu


2 Answers

Consider the following method:

public bool IsNullString<T>(T item) {
    return typeof(T) == typeof(string) && item == null;
}

Yes, this is a pathetically stupid method and using generics is pointless here, but you'll see the point in a moment.

Now consider

bool first = IsNullString<string>(null);
bool second = IsNullString<Foo>(null);

bool third = IsNullString(null);

In the first and second, the compiler can clearly distinguish the type of T (no inference is needed). In the third, how the compiler infer what T is? In particular, it can't distinguish between T == string and T == Foo, or any other type for that matter. Therefore, the compiler has to give you a compile-time error.

If you want to get around this, you either need to cast null

EqualTo((object)null);

or explicitly state the type

EqualTo<object>(null)

or define an overload

private static Matcher<object> EqualTo(object item) {
    return new IsEqual<object>(item);
}
like image 119
jason Avatar answered Oct 11 '22 13:10

jason


Not possible without explicitly specifying a T or doing a cast. Generics are compile time constructs and as such if the compiler can't figure out the type at compile time, then it won't compile (as you're seeing).

like image 28
Vadim Avatar answered Oct 11 '22 12:10

Vadim