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.
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));
}
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With