This question already has an answer here:
For any given type i want to know its default value.
In C#, there is a keyword called default for doing this like
object obj = default(Decimal);
but I have an instance of Type (called myType) and if I say this,
object obj = default(myType);
it doesn't work
Is there any good way of doing this? I know that a huge switch block will work but thats not a good choice.
Here's a function that will return the default value for a nullable type (in other words, it returns 0 for both
Decimal
andDecimal?
):Having solved this problem in my own systems, here is a method for correctly determining the default value of an arbitrary Type at run time, which has been tested against thousands of Types:
In these examples, the GetDefault method is implemented in the static class DefaultValue. Call this method with a statement like:
To use the GetDefault method as an extension method for Type, call it like this:
This second, Type-extension approach is a simpler client-code syntax, since it removes the need to reference the containing DefaultValue class qualifier on the call.
The above run time form of GetDefault works with identical semantics as the primitive C# 'default' keyword, and produces the same results.
To use a generic form of GetDefault, you may access the following function:
A call to the generic form could be something like:
Of course, the above generic form of GetDefault is unnecessary for C#, since it works the same as default(T). It is only useful for a .NET language that does not support the 'default' keyword but which supports generic types. In most cases, the generic form is unnecessary.
A useful corollary method is one to determine whether an object contains the default value for its Type. I also rely on the following IsObjectSetToDefault method for that purpose:
The above
IsObjectSetToDefault
method can either be called in its native form or accessed as a Type-class extension.What do you mean by "Default Value"? All reference Types ("class") have null as default value, while all value types will have their default values according to this table.
How about something like...
It produces the following output:
You could also add it as an extension method to System.Type:
There's really only two possibilities:
null
for reference types andnew myType()
for value types (which corresponds to 0 for int, float, etc) So you really only need to account for two cases:(Because value types always have a default constructor, that call to Activator.CreateInstance will never fail).