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

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
 
G

Guest

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);
 
G

Guest

....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.
 
J

Jon Skeet [C# MVP]

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;
}
 
G

Guest

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top