Getting the default value of some value type

I am using reflection to check an object’s fields. I only want to do work on fields that are assigned a non-default value, so non-null for reference types, and values other than false/0/0.0 for bool/int/float etc.

C# 2.0 has a default(T) keyword, but this only works when you know the type T at compile time. So default(int) returns 0, but you can’t do default(typeof(int)) or default(myFieldInfo.FieldType).

Avner Kashtan has a good summary and a work-around using reflection, which involves calling the default constructor for value types using Activator.CreateInstance(myFieldInfo.FieldType) and comparing it to the value you have.

Comments