Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 663
smartcaveman Avatar asked Aug 15 '11 17:08

smartcaveman


People also ask

What is the default value of a reference type?

The default value of a reference type is null . It means that if a reference type is a static class member or an instance field and not assigned an initial value explicitly, it will be initialized automatically and assigned the value of null .

Which is the default type?

Type is the attribute that displays type of <input> elements. Its default type is text.


2 Answers

Old question but the accepted answer doesn't work for me so I submit this (probably can be made better):

public static object GetDefault(this Type type)
{   
    if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
    {
        var valueProperty = type.GetProperty("Value");
        type = valueProperty.PropertyType;
    }

    return type.IsValueType ? Activator.CreateInstance(type) : null;
}

With the following results:

typeof(int).GetDefault();       // returns 0
typeof(int?).GetDefault();      // returns 0
typeof(DateTime).GetDefault();  // returns 01/01/0001 00:00:00
typeof(DateTime?).GetDefault(); // returns 01/01/0001 00:00:00
typeof(string).GetDefault();    // returns null
typeof(Exception).GetDefault(); // returns null
like image 97
dav_i Avatar answered Oct 18 '22 23:10

dav_i


I would require ValueType as the parameter to simplify:

static bool IsDefault(ValueType value){
   var @default = Activator.CreateInstance(value.GetType());
   return value.Equals(@default);  
}
like image 44
Gene C Avatar answered Oct 18 '22 22:10

Gene C