Home > Enterprise >  What is the best way of getting default value from Type
What is the best way of getting default value from Type

Time:12-01

I have Type and I want to get the default value. For example, if Type is class or nullable I should get null. But if it is integer, DateTime. decimal, ... I should get 0. What is the best way of doing this?

CodePudding user response:

I expect you can use something like this:

public static object GetDefaultValue(Type type)
{
    return type.IsClass ? null : Activator.CreateInstance(type);
}

Try it online

CodePudding user response:

From your description you can just use a default expression or literal.

int a = default(int);
int a = default;

Default values of C# types (C# reference)

Type Default value
Any reference type null
Anybuilt-in integral numeric type 0 (zero)
Any built-in floating-point numeric type 0 (zero)
bool false
char '\0' (U 0000)
enum The value produced by the expression (E)0, where E is the enum identifier.
struct The value produced by setting all value-type fields to their default values and all reference-type fields to null.
Any nullable value type An instance for which the HasValue property is false and the Value property is undefined. That default value is also known as the null value of a nullable value type.

CodePudding user response:

You could use Activator.CreateInstance to generate an empty variable of the type and then check the value of it :)

  • Related