Detecting nullable types in C#
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
开发者_C百科 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!
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;
}
This might be a long shot, but could you use generics and a method overload to let the compiler work this out for you?
public bool IsValid<T>(string propertyName, T propertyValue)
{
// ...
}
public bool IsValid<T>(string propertyName, T? propertyValue) where T : struct
{
// ...
}
Another thought: is your code attempting to go through every property value on an object? If so, you can use reflection to iterate through the properties, and get their types that way.
Edit
Using Nullable.GetUnderlyingType
as Denis suggested in his answer would get around the need to use an overload.
精彩评论