When supplied with an integer (or other value type) boxed as a object
, I'm pretty sure there is no way to use default()
(returns the default value of a given type) on it directly to return the underlying boxed default value, is this correct?
I'd rather make a call on object
in a single operation without having to write a load of conditionals as follows:
public object GetDefaultVal(object obj){
if(obj is Guid){
return default(Guid);
}
if(obj is double){
return default(double);
}
....
}
Assuming you can't change the method to be generic, you can just use the fact that all value types provide a parameterless constructor, so you can call Activator.CreateInstance
:
public object GetDefaultValue(object obj)
{
Type type = obj.GetType();
return type.IsValueType ? Activator.CreateInstance(type) : null;
}
(The default value for all reference types is null.)
See more on this question at Stackoverflow