3

Possible Duplicate:
C# - Programmatic equivalent of default(Type)

Is there a method or property in the Type class (or elsewhere) that I can use to find the value of default(T)?

Community
  • 1
  • 1
Felix Ungman
  • 502
  • 2
  • 9

2 Answers2

5

Just check type.IsValueType; if that is true use Activator.CreateInstance(type) - otherwise it is null.

It also helps that you can pass null to SetValue on a PropertyInfo or FieldInfo and it will work for value-types with even for int, float etc.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
3
object obj = type.IsValueType ? Activator.CreateInstance(type) : null;
abatishchev
  • 98,240
  • 88
  • 296
  • 433