Null or default comparison of generic argument in C#

Question :

Null or default comparison of generic argument in C#,

Answer :

I have a generic method defined like this:

public void MyMethod(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.


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

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

This will match:

  • null for classes
  • null (empty) for Nullable
  • zero/false/etc for other structs

That’s the answer Null or default comparison of generic argument in C#, Hope this helps those looking for an answer. Then we suggest to do a search for the next question and find the answer only on our site.

Disclaimer :

The answers provided above are only to be used to guide the learning process. The questions above are open-ended questions, meaning that many answers are not fixed as above. I hope this article can be useful, Thank you

Read More  Install Visual Studio 2008 Sp1 on “D” Drive