Search code examples
c#reflectionnullabletypechecking

Identify if a Type is *either* of int or Nullable<int>


Reflection code.

I can check if myTypeObject == typeof(decimal) || myTypeObject == typeof(decimal?)

Is there any way to do that without repeating decimal?

I'm guessing something along the lines of:

myRealTypeObject = myTypeObject.IsNullable() ? myTypeObject.GetTypeInsideNullability() : myTypeObject;
myRealTypeObject == typeof(decimal)

Solution

  • You can use Nullable.GetUnderlyingType which returns null if the input type is not nullable:

    var myRealTypeObject = Nullable.GetUnderlyingType(myTypeObject) ?? myTypeObject;
    

    if instead you have have some object you want to check you can just use is (or as):

    bool isDecimal = boxedDecimal is decimal?;