Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's a maintainable way to determine if a value is set to its type's default value?

Tags:

c#

.net

Say I have some code such as the following:

var someCollection = new int[] {};
var result = someCollection.SingleOrDefault();

I then want to determine if result was the default value. However, I want to do so in a maintainable way so that if the element type of someCollection changes, the rest of the code doesn't require changing.

The way this typically seems to be done (in a general sense) is result == null. In this case, of course, the type is not a reference type, so this won't work.

An improvement that avoids this assumption is result == default(int). However, changing the element type would also require changing the argument to default, so the requirement of only changing the type in one place is still not met.

Acceptance Criteria

  1. Built-in logic is preferred over custom logic.
  2. Elegant and concise code is preferred.
  3. Efficient code is preferred. (For reference types, only a reference comparison should occur.)
like image 776
Sam Avatar asked Mar 05 '13 23:03

Sam


3 Answers

You can use the default keyword. Since you don't know what the type will be, you can use generics.

public bool IsDefault<T>(T value)
{
    return EqualityComparer<T>.Default.Equals(value, default(T));
}
like image 89
keyboardP Avatar answered Nov 08 '22 23:11

keyboardP


Stealing from Sam, and improving it:

public static bool IsDefault<T>(this T value)
{
    return value == null || value.Equals(default(T));
}

No need for a type check. The JIT will make it work because it knows what T is at JIT time.

Note that if the type overrides Equals then it might say false even when it is default(T) and it might say true even when it is not. – commented by Eric Lippert

like image 22
usr Avatar answered Nov 08 '22 21:11

usr


I think this will work.

public static bool IsDefault<T>(this T value)
{
    var isValueType = typeof(T).IsValueType;

    if (isValueType)
        return value.Equals(default(T));
    else
        return value == null;
}

However, for value types, I figure this will call their overloaded Equals methods, which may or may not be a problem.

like image 36
Sam Avatar answered Nov 08 '22 23:11

Sam