0

I am examining an object via reflection, and I want to print those properties which have non-default values. Given a signature like this:

public static bool IsDefaultValue(PropertyInfo prop, object o)
{
 //returns true if the given property's value on o is the default value for the property type
}

How could this be implemented?

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589
  • `return prop.GetType().IsValueType && o != null ? Activator.CreateInstance(o.GetType()).Equals(o) : o == null;` ? –  Jul 10 '20 at 15:57
  • @OlivierRogier For classes, you should use `ReferenceEquals` to make sure reference comparison is used even if `==` is overloaded (it would work in this case but using it makes your intent clear). For structs, `Equals` may be overridden and implement a different logic than the default one (by value). A framework method to force comparison by value would be useful here. – vc 74 Jul 10 '20 at 16:00
  • @vc74 `ReferenceEquals` instead of what ? –  Jul 10 '20 at 16:08
  • @OlivierRogier `!object.ReferenceEquals(o, null)` instead of `o != null`. Not a big deal in this case since the operator will be resolved at compile time and default to the base object implementation. However `Equals` is resolved at runtime so it's trickier to force the default behavior (comparison by value) and avoid an overridden implementation. – vc 74 Jul 10 '20 at 17:35

0 Answers0