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?
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 .
Type is the attribute that displays type of <input> elements. Its default type is text.
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
I would require ValueType
as the parameter to simplify:
static bool IsDefault(ValueType value){
var @default = Activator.CreateInstance(value.GetType());
return value.Equals(@default);
}
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