How to find default value for value type

A

Andrus

How to create method

object DefaultValue( Type valueType ) { ... }

Which returns defualt value for passed value type ?

DefaultValue(typeof(int))
DefaultValue(typeof(decimal))

should return 0

DefaultValue(typeof(bool))

should return false

etc.

I can use

if ( valuetype==typeof(int) )
return 0;
else
if ( valuetype==typeof(bool) )
return false;
etc.

but its looks ugly. Is there a better solution ?

Andrus.
 
M

Mythran

Andrus said:
How to create method

object DefaultValue( Type valueType ) { ... }

Which returns defualt value for passed value type ?

DefaultValue(typeof(int)) DefaultValue(typeof(decimal))
should return 0

DefaultValue(typeof(bool))
should return false

etc.

I can use
if ( valuetype==typeof(int) )
return 0;
else
if ( valuetype==typeof(bool) )
return false;
etc.

but its looks ugly. Is there a better solution ?

Andrus.

The 'default' keyword for getting the 'default' value is 'default'.

int defaultIntValue = default(int);

HTH,
Mythran
 
A

Arne Vajhøj

Andrus said:
How to create method

object DefaultValue( Type valueType ) { ... }

Which returns defualt value for passed value type ?

DefaultValue(typeof(int)) DefaultValue(typeof(decimal))
should return 0

DefaultValue(typeof(bool))
should return false

etc.

I can use
if ( valuetype==typeof(int) )
return 0;
else
if ( valuetype==typeof(bool) )
return false;
etc.

but its looks ugly. Is there a better solution ?

Two suggestions:

public static object DefaultValue1<T>()
{
return default(T);
}
public static object DefaultValue2(Type t)
{
return Activator.CreateInstance(t);
}

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

Top