Alexandre
Alexandre

Reputation: 13308

Check for null for struct in C# if struct isn't nullable

I have some generic method

T SomeMethod(Func<T> func){
   T result = func();
     if (result != null)
       { //.....}
}

It works good if T is class. But what should I do if T is struct? How can I check if result == default(T) in case if T is struct?

P.S. I don't want to use the constraint where T: class or Nullable types.

Upvotes: 5

Views: 8808

Answers (3)

Sergey Sirotkin
Sergey Sirotkin

Reputation: 1677

Consider using default(T):

private T SomeMethod<T>(Func<T> func)
{
  var result = func();
  if (result.Equals(default(T)))
  {
    // handling ...
    return default(T);
  }
  return result;
}

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

A more idiomatic way of doing this would be to follow the lead of things like int.TryParse.

public delegate bool TryFunction<T>(out T result);

T SomeMethod(TryFunction<T> func)
{
    T value;

    if(func(out value))
    {

    }
}

Upvotes: 3

JaredPar
JaredPar

Reputation: 754943

If T is compiled to be a struct then the comparison with null will always evaluate to false. This is covered in section 7.9.6 of the C# language spec

If an operand of a type parameter type T is compared to null, and the runtime type of T is a value type, the result of the comparison is false.

Upvotes: 3

Related Questions