Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In .NET, at runtime: How to get the default value of a type from a Type object? [duplicate]

Possible Duplicate:
Default value of a type

In C#, to get the default value of a Type, i can write...

var DefaultValue = default(bool);` 

But, how to get the same default value for a supplied Type variable?.

public object GetDefaultValue(Type ObjectType) {     return Type.GetDefaultValue();  // This is what I need } 

Or, in other words, what is the implementation of the "default" keyword?

like image 521
Néstor Sánchez A. Avatar asked Apr 21 '10 21:04

Néstor Sánchez A.


People also ask

What is the default value of VAR in C#?

Depends on the type of the variable. If the type can be null then it's default value will be null.

What does default () do in C#?

The default keyword returns the "default" or "empty" value for a variable of the requested type. For all reference types (defined with class , delegate , etc), this is null . For value types (defined with struct , enum , etc) it's an all-zeroes value (for example, int 0 , DateTime 0001-01-01 00:00:00 , etc).

How can we set default value to the variable?

You can set the default values for variables by adding ! default flag to the end of the variable value. It will not re-assign the value, if it is already assigned to the variable.


1 Answers

I think that Frederik's function should in fact look like this:

public object GetDefaultValue(Type t) {     if (t.IsValueType)     {         return Activator.CreateInstance(t);     }     else     {         return null;     } } 
like image 53
michalburger1 Avatar answered Sep 24 '22 08:09

michalburger1