user208662
user208662

Reputation: 10997

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
  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!

Upvotes: 7

Views: 428

Answers (3)

Denis Pitcher
Denis Pitcher

Reputation: 3240

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;
}

Upvotes: 2

Richard Ev
Richard Ev

Reputation: 54127

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.

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1503110

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.

Upvotes: 11

Related Questions