How to get a default instance of built-in type?

  • Thread starter Thread starter Michael Bray
  • Start date Start date
M

Michael Bray

Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));

I have tried:

return t.TypeInitializer.Invoke(null);

but it says "Type initializer is not callable."

-mdb
 
If you use generics you can use the default keyword...

Otherwise you can use Reflect to get the default c'tor, if it exists (i.e.
perform a check):
return t.GetConstructor(BindingFlags.Instance
| BindingFlags.Default
| BindingFlags.Public
, null
, Type.EmptyTypes
, null).Invoke(null);
 
....forgot an example for generics:
public static void GetDefaultValue<T> ( out T value )
{
value = default(T);
}
// ...
string text;
GetDefaultValue(out text);

Notice you don't have to deal with typeof at all... Keep in mind, that
won't create an instance for reference types--which will be null.
 
Michael Bray said:
Lets say I want to get the default value for a system type... how would I
implement the following function:

public object DefaultValueOfType(Type t)
{
return ????;
}

I want to be able to call it like this:

DefaultValueOfType(typeof(string));
DefaultValueOfType(typeof(int));
DefaultValueOfType(typeof(double));

For reference types, the default value is always null. For value types,
the default value can be obtained by calling the parameterless
constructor which is guaranteed to exist:

static object DefaultValueOfType (Type t)
{
return t.IsValueType ? Activator.CreateInstance(t)
: null;
}
 
Peter said:
Notice you don't have to deal with typeof at all... Keep in mind, that
won't create an instance for reference types--which will be null.

Maybe new was better than default.

public static T GetDefault<T>() where T : new()
{
return new T();
}

will work for reference types with a no arg constructor.

Arne
 
Back
Top