简体   繁体   中英

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 ?

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

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

    }
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM