I'm writing an ObjectHasValueConverter : IValueConverter
for WPF.
The relevant function is Convert(object value, ...)
. I want essentially want to do
return value != default(value.GetType())
Unfortunately, it seems default
is a compile-time keyword and IValueConverter
doesn't have a generic equivalent, so I can't just do default(T)
.
Obviously if value is an instance of a class or an array I can just check for null.
if (value.GetType().IsValueType | value.GetType().IsArray)
{
return value != null;
}
I have a special case for string
s, returning !string.IsNullOrWhitespace(value)
. For structs and other primitives, I'm hoping there's something cleaner than
if (value is int | value is short | value is long | ...)
{
return (int)value != 0;
}
if (value is float | value is double)
{
return (double)value != 0;
}
if (value is bool)
{
return !(bool)value;
}
...
I've scoured SO before writing this, but all the answers I found had to do with reflection and getting the members of a value type. I didn't find anything relating to types that are put on the stack.