Default value of any type

  • Thread starter Thread starter GeezerButler
  • Start date Start date
G

GeezerButler

For any given type i want to know its default value.

There is a neat keyword called default for doing this like
object x = default(DateTime);
but I have an instance of Type (called someType) and something like
this cant work
object x = default(someType);


Is there any nice way of doing this? I dont really want to write a
huge switch block enumerating all types in .NET !
 
The default keyword returns null for reference types. Use the GetConstructor
method of the Type class, passing it an empty Type array, to get a
ConstructorInfo instance, and then call the Invoke method, passing null to
it:

object x = someType.GetConstructor(System.Type.EmptyTypes).Invoke(null);

--
HTH,

Kevin Spencer
Chicken Salad Surgeon
Microsoft MVP
 
For any given type i want to know its default value.

<snip>

Please see the replies in the C# group - and please don't multipost
like this. It fragments discussion and wastes time.

Jon
 
<snip>

Please see the replies in the C# group - and please don't multipost
like this. It fragments discussion and wastes time.

Jon

Thanks and apologies for the cross post.
 
Back
Top