Null or default comparison of generic argument in

2019-01-04 04:48发布

I have a generic method defined like this:

public void MyMethod<T>(T myArgument)

The first thing I want to do is check if the value of myArgument is the default value for that type, something like this:

if (myArgument == default(T))

But this doesn't compile because I haven't guaranteed that T will implement the == operator. So I switched the code to this:

if (myArgument.Equals(default(T)))

Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:

if (myArgument == null || myArgument.Equals(default(T)))

Now this feels redundant to me. ReSharper is even suggesting that I change the myArgument == null part into myArgument == default(T) which is where I started. Is there a better way to solve this problem?

I need to support both references types and value types.

标签: c# generics
12条回答
成全新的幸福
2楼-- · 2019-01-04 05:20

To avoid boxing, the best way to compare generics for equality is with EqualityComparer<T>.Default. This respects IEquatable<T> (without boxing) as well as object.Equals, and handles all the Nullable<T> "lifted" nuances. Hence:

if(EqualityComparer<T>.Default.Equals(obj, default(T))) {
    return obj;
}

This will match:

  • null for classes
  • null (empty) for Nullable<T>
  • zero/false/etc for other structs
查看更多
ら.Afraid
3楼-- · 2019-01-04 05:20

I was able to locate a Microsoft Connect article that discusses this issue in some detail:

Unfortunately, this behavior is by design and there is not an easy solution to enable use of with type parameters that may contain value types.

If the types are known to be reference types, the default overload of defined on object tests variables for reference equality, although a type may specify its own custom overload. The compiler determines which overload to use based on the static type of the variable (the determination is not polymorphic). Therefore, if you change your example to constrain the generic type parameter T to a non-sealed reference type (such as Exception), the compiler can determine the specific overload to use and the following code would compile:

public class Test<T> where T : Exception

If the types are known to be value types, performs specific value equality tests based on the exact types used. There is no good "default" comparison here since reference comparisons are not meaningful on value types and the compiler cannot know which specific value comparison to emit. The compiler could emit a call to ValueType.Equals(Object) but this method uses reflection and is quite inefficient compared to the specific value comparisons. Therefore, even if you were to specify a value-type constraint on T, there is nothing reasonable for the compiler to generate here:

public class Test<T> where T : struct

In the case you presented, where the compiler does not even know whether T is a value or reference type, there is similarly nothing to generate that would be valid for all possible types. A reference comparison would not be valid for value types and some sort of value comparison would be unexpected for reference types that do not overload.

Here is what you can do...

I have validated that both of these methods work for a generic comparison of reference and value types:

object.Equals(param, default(T))

or

EqualityComparer<T>.Default.Equals(param, default(T))

To do comparisons with the "==" operator you will need to use one of these methods:

If all cases of T derive from a known base class you can let the compiler know using generic type restrictions.

public void MyMethod<T>(T myArgument) where T : MyBase

The compiler then recognizes how to perform operations on MyBase and will not throw the "Operator '==' cannot be applied to operands of type 'T' and 'T'" error that you are seeing now.

Another option would be to restrict T to any type that implements IComparable.

public void MyMethod<T>(T myArgument) where T : IComparable

And then use the CompareTo method defined by the IComparable interface.

查看更多
成全新的幸福
4楼-- · 2019-01-04 05:22

There is going to be a problem here -

If you're going to allow this to work for any type, default(T) will always be null for reference types, and 0 (or struct full of 0) for value types.

This is probably not the behavior you're after, though. If you want this to work in a generic way, you probably need to use reflection to check the type of T, and handle value types different than reference types.

Alternatively, you could put an interface constraint on this, and the interface could provide a way to check against the default of the class/struct.

查看更多
地球回转人心会变
5楼-- · 2019-01-04 05:22

@ilitirit:

public class Class<T> where T : IComparable
{
    public T Value { get; set; }
    public void MyMethod(T val)
    {
        if (Value == val)
            return;
    }
}

Operator '==' cannot be applied to operands of type 'T' and 'T'

I can't think of a way to do this without the explicit null test followed by invoking the Equals method or object.Equals as suggested above.

You can devise a solution using System.Comparison but really that's going to end up with way more lines of code and increase complexity substantially.

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-04 05:23

Try this:

if (EqualityComparer<T>.Default.Equals(myArgument, default(T)))

that should compile, and do what you want.

查看更多
放荡不羁爱自由
7楼-- · 2019-01-04 05:25

I think you were close.

if (myArgument.Equals(default(T)))

Now this compiles, but will fail if myArgument is null, which is part of what I'm testing for. I can add an explicit null check like this:

You just need to reverse the object on which the equals is being called for an elegant null-safe approach.

default(T).Equals(myArgument);
查看更多
登录 后发表回答