Dilshod K
Dilshod K

Reputation: 3032

What is the best way of getting default value from Type

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?

Upvotes: 2

Views: 1660

Answers (3)

TheGeneral
TheGeneral

Reputation: 81493

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.

Upvotes: 4

ProgrammingLlama
ProgrammingLlama

Reputation: 38767

I expect you can use something like this:

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

Try it online

Upvotes: 3

SuspiciousGoose
SuspiciousGoose

Reputation: 74

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

Upvotes: 0

Related Questions