Wednesday, September 15, 2010

default(Type)

Just another stupid question. In C# there is a default keyword, that allows to get a default value for a given type - null for reference types and some defined value for value types. Actually, if T is value type, "default(T)" is equals to "new T()". This keyword works in compile time and a compiler will substitute it with corresponding value.
But how could I get a default value in runtime, when I have System.Type object?

The answer is
Activator.CreateInstance(type)
as far as value type always has parameter-less constructor.

2 comments: