I'm using reflection to loop through a Type
's properties and set certain types to their default. Now, I could do a switch on the type and set the default(Type)
explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?
The default keyword returns the "default" or "empty" value for a variable of the requested type. For all reference types (defined with class , delegate , etc), this is null . For value types (defined with struct , enum , etc) it's an all-zeroes value (for example, int 0 , DateTime 0001-01-01 00:00:00 , etc).
public static object GetDefault(Type type) { if(type.IsValueType) { return Activator.CreateInstance(type); } return null; }
In the newer version of .net such as .net standard, type.IsValueType
needs to be written as type.GetTypeInfo().IsValueType
Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:
public object GetDefault(Type t) { return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null); } public T GetDefaultGeneric<T>() { return default(T); }
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