Alex Rivera | Logout

C#: Alternative to GenericType == null

Asked 2009-02-19T14:33:07.513
22

I need to check a generic object for null, or default(T). But I have a problem... Currently I have done it like this:

if (typeof(T).IsValueType)
{
  if(default(T).Equals(thing))
    // Do something
  else
    // Do something else
}
else
{
  if(thing == null)
    // Do something
  else
    // Do something else
}

But then I end up repeating myself... which I don't like. The problem is the following:

thing == null;

Here ReSharper warns about Possible compare of value type with 'null'.

thing == default(T);

Here I get compiler error: Cannot apply operator '==' to operands of type 'T' and 'T'.

thing.Equals(null|default(T));

thing can obviously be null (that's why I have to check!), so will cause NullReferenceException.

null|default(T).Equals(thing);

null and default(T) is very often null as well...

Is there a clean way to do this??

Edit
Report

2 Answers

2

Best thing I can think of at the moment is:

return value == null || value.Equals(default(T));

Edit:

Apparently, there's a static object.Equals method I was not aware of:

return object.Equals(value, default(T));

This is better.

answered 2009-02-19T14:41:07.713
0

With Tests:

public class DefaultOrNullChecker<T>  {
    public bool Check(object x) {
        return object.ReferenceEquals(x, null) || x.Equals(default(T));
    }
}
[TestFixture]
public class Tests {
    [Test]  public void when_T_is_reference_type() { 
        Assert.IsFalse(new DefaultOrNullChecker<Exception>().Check(new Exception()));}
    [Test] public void when_T_is_value_type() { 
        Assert.IsFalse(new DefaultOrNullChecker<int>().Check(123)); }
    [Test] public void when_T_is_null() {
        Assert.IsTrue(new DefaultOrNullChecker<Exception>().Check(null));}
    [Test] public void when_T_is_default_value() { 
        Assert.IsTrue(new DefaultOrNullChecker<int>().Check(0)); }
}
answered 2009-02-19T14:45:39.310

Your Answer