Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatic equivalent of default(Type)

I'm using reflection to loop through a Type's properties and set certain types to their default. Now, I could do a switch on the type and set the default(Type) explicitly, but I'd rather do it in one line. Is there a programmatic equivalent of default?

like image 447
tags2k Avatar asked Nov 28 '08 10:11

tags2k


People also ask

What is default() 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).


2 Answers

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type) {    if(type.IsValueType)    {       return Activator.CreateInstance(type);    }    return null; } 

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

like image 192
Dror Helper Avatar answered Sep 30 '22 18:09

Dror Helper


Why not call the method that returns default(T) with reflection ? You can use GetDefault of any type with:

    public object GetDefault(Type t)     {         return this.GetType().GetMethod("GetDefaultGeneric").MakeGenericMethod(t).Invoke(this, null);     }      public T GetDefaultGeneric<T>()     {         return default(T);     } 
like image 26
Drakarah Avatar answered Sep 30 '22 19:09

Drakarah