How to implement "default(T)" for a given Type

J

Jeff Brown

Hi,

I'm trying to implement the functionality of the generic expression,
"default(T)", but for a given instance of the Type class.

The ideal would be if the Type class had a method like "object
Type.MakeDefaultInstance()" -- but it doesn't.

Here's my attempt, but it seems rather kludgy. Is there a better way?

static public object MakeDefaultInstance(Type type)
{
if (type.IsValueType)
return Activator.CreateInstance(type);
else
return null;
}

Thanks,
Jeff Brown
 
M

Mattias Sjögren

Here's my attempt, but it seems rather kludgy. Is there a better way?

Really? I think it's rather nice and clean, and probably the way I'd
do it.


Mattias
 

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

Top