6

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.

Community
  • 1
  • 1
Guulh
  • 284
  • 2
  • 7
  • Welcome to expression world? http://stackoverflow.com/questions/6582259/fast-creation-of-objects-instead-of-activator-createinstancetype :) – nawfal Apr 24 '13 at 12:05

2 Answers2

7

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.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
5

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
JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454
  • That is generics (which the OP wants to avoid), and isn't the same as "default" - it should return null for classes. – Marc Gravell Feb 06 '09 at 13:40
  • Thank you very much ! I know Reflection is uber-powerfull, but I'm reluctant to use it when there are simple solutions. But if there's no choice, let's go with it :) – Guulh Feb 06 '09 at 13:41
  • @Marc, very true, I was mainly trying to give an example showing that Activator is not an *evil* class – JaredPar Feb 06 '09 at 13:43
  • 1
    I quite agree - simply that it doesn't seem to answer the original question... Oh well, the OP is happy, at least... ;-p – Marc Gravell Feb 06 '09 at 13:45