Search code examples
c#reflectionstructdefaultdefault-constructor

How to get the default value for a ValueType Type with reflection


If I have a generic type parameter that is a value type and I want to know if a value is equal to the default I test it like this:

static bool IsDefault<T>(T value){
    where T: struct
    return value.Equals(default(T));
}

If I don't have a generic type parameter, then it seems like I would have to use reflection. If the method has to work for all value types, then Is there a better way to perform this test than what I am doing here? :

static bool IsDefault(object value){
   if(!(value is ValueType)){
      throw new ArgumentException("Precondition failed: Must be a ValueType", "value");
   }
   var @default = Activator.CreateInstance(value.GetType());
   return value.Equals(@default);  
}

On a side note, Is there anything I am not considering here with respect to evaluating Nullable structs?


Solution

  • I have found the following extension methods useful and will work for all types:

    public static object GetDefault(this Type t)
    {
        return t.IsValueType ? Activator.CreateInstance(t) : null;
    }
    
    public static T GetDefault<T>()
    {
        var t = typeof(T);
        return (T) GetDefault(t);
    }
    
    public static bool IsDefault<T>(T other)
    {
        T defaultValue = GetDefault<T>();
        if (other == null) return defaultValue == null;
        return other.Equals(defaultValue);
    }