Possible Duplicate:
Default value of a type
In C#, to get the default value of a Type, i can write...
var DefaultValue = default(bool);`
But, how to get the same default value for a supplied Type variable?.
public object GetDefaultValue(Type ObjectType) { return Type.GetDefaultValue(); // This is what I need }
Or, in other words, what is the implementation of the "default" keyword?
Depends on the type of the variable. If the type can be null then it's default value will be null.
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).
You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.
I think that Frederik's function should in fact look like this:
public object GetDefaultValue(Type t) { if (t.IsValueType) { return Activator.CreateInstance(t); } else { return null; } }
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