Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the default value of a type in a non-generic way?

I know the "default" keyword returns the default value of a statically determined type, as shown for instance in this question.

However, given an instance of a type, is there a simple way to get the default value of this type, dynamically ? The only way I found while googling is this :

static object DefaultValue(Type myType)
{
    if (!myType.IsValueType)
        return null;
    else
        return Activator.CreateInstance(myType);
}

But I'd like to avoid the Activator class if possible.

like image 887
Guulh Avatar asked Feb 06 '09 13:02

Guulh


2 Answers

Why do you want to avoid Activator? Basically that is the way of doing it.

I mean, you could write a generic method and then call that via reflection, but that's a pretty hideous "long cut" just to avoid Activator.

like image 114
Jon Skeet Avatar answered Oct 20 '22 18:10

Jon Skeet


This is likely your best route.

I wouldn't be afraid of using the Activator class here. This is a pretty standard class that is depended on by the compilers. For instance this VB code

Public Sub Example(Of T as New)()
  Dim x = new T()
End Sub

Translates into roughly this code

Public Sub Example(Of T As New)()
  Dim x = Activator.CreateInstance(OF T)
ENd Sub
like image 5
JaredPar Avatar answered Oct 20 '22 19:10

JaredPar