Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detecting nullable types in C#

Tags:

c#

nullable

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!

like image 469
user208662 Avatar asked Jun 13 '11 13:06

user208662


People also ask

How do you check if a type is nullable?

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 can you check a nullable variable for any type of value in C#?

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.

Does HasValue check for 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.

How check double value is null or not in C#?

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.


2 Answers

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.

like image 156
Jon Skeet Avatar answered Sep 19 '22 17:09

Jon Skeet


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;
}
like image 23
Denis Pitcher Avatar answered Sep 19 '22 17:09

Denis Pitcher