I have a method that is defined like such:
public bool IsValid(string propertyName, object propertyValue)
{
bool isValid = true;
// Validate property based on type here
return isValid;
}
I would like to do something like:
if (propertyValue is bool?)
{
// Ensure that the property is true
}
My challenge is, I'm not sure how to detect whether my propertyValue is a nullable bool or not. Can someone tell me how to do this?
Thank you!
If column to be added is nullable type, we need to explicitly set it. To check if PropertyType is nullable, we can use `System. Nullable. GetUnderlyingType(Type nullableType)`, see example below and reference here.
How to access the value of Nullable type variables? You cannot directly access the value of the Nullable type. You have to use GetValueOrDefault() method to get an original assigned value if it is not null. You will get the default value if it is null.
The HasValue property returns true if the variable contains a value, or false if it is null. You can only use == and != operators with a nullable type. For other comparison use the Nullable static class.
IsNaN() is a Double struct method. This method is used to check whether the specified value is not a number (NaN). Return Type: This function returns a Boolean value i.e. True, if specified value is not a number(NaN), otherwise returns False. Code: To demonstrate the Double.
The value of propertyValue
could never be a Nullable<bool>
. As the type of propertyValue
is object
, any value types will be boxed... and if you box a nullable value type value, it becomes either a null reference, or the boxed value of the underlying non-nullable type.
In other words, you'd need to find the type without relying on the value... if you can give us more context for what you're trying to achieve, we may be able to help you more.
You may need to use generics for this but I think you can check the nullable underlying type of propertyvalue and if it's bool, it's a nullable bool.
Type fieldType = Nullable.GetUnderlyingType(typeof(propertyvalue));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
return true;
}
Otherwise try using a generic
public bool IsValid<T>(T propertyvalue)
{
Type fieldType = Nullable.GetUnderlyingType(typeof(T));
if (object.ReferenceEquals(fieldType, typeof(bool))) {
return true;
}
return false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With