patterncsharpCritical
Programmatic equivalent of default(Type)
Viewed 0 times
equivalentdefaulttypeprogrammatic
Problem
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?Solution
- 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().IsValueTypeCode Snippets
public static object GetDefault(Type type)
{
if(type.IsValueType)
{
return Activator.CreateInstance(type);
}
return null;
}Context
Stack Overflow Q#325426, score: 821
Revisions (0)
No revisions yet.