Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Equivalent of default(T) using reflection [duplicate]

Possible Duplicate:
C# - Programmatic equivalent of default(Type)

Is there a method or property in the Type class (or elsewhere) that I can use to find the value of default(T)?

like image 555
Felix Ungman Avatar asked Apr 30 '26 20:04

Felix Ungman


1 Answers

Just check type.IsValueType; if that is true use Activator.CreateInstance(type) - otherwise it is null.

It also helps that you can pass null to SetValue on a PropertyInfo or FieldInfo and it will work for value-types with even for int, float etc.

like image 92
Marc Gravell Avatar answered May 02 '26 08:05

Marc Gravell



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!