locked
how to get type of a nullable type when the underlying value is null? RRS feed

  • Question

  • I tried to use following code to get "System.Decimal" but I received this undesirable exception! :(

    decimal? x = null; Console.WriteLine(x.GetType()); //I will get an NullReferenceException.

    maybe  one solution is:

    decimal? x = null;
    Console.WriteLine(x.GetValueOrDefault().GetType())

    but i presume there is a better way. 

    Wednesday, April 3, 2013 7:09 AM

Answers

  • You can try this

    using System;
    using System.Reflection;
    using System.Linq.Expressions;
    
    namespace Test
    {
      class Mymemberinfo
      {
        public static int Main()
        {
          decimal? x = null;
          Type xType = GetObjectType(() => x);
          Type genericTypeArgument = GetObjectType(() => x).GetGenericArguments()[0];
          return 0;
        }
        public static Type GetObjectType(Expression<Func<object>> expr)
        {
          var obj =  ((UnaryExpression)expr.Body).Operand;
          return (Type)((PropertyInfo)obj.GetType()
            .GetProperty("Type", BindingFlags.Instance | BindingFlags.Public)).GetValue(obj);
        }
      }
    }

    but your code better.

    • Marked as answer by zdbdam Wednesday, April 3, 2013 11:40 AM
    Wednesday, April 3, 2013 11:02 AM

All replies

  • You can't do anything with x if it is null. You have to set it to a non-null value before you can operate on it in any way
    Wednesday, April 3, 2013 7:31 AM
  • I know, GetType() method, evaluate the object of an instance, not the reference. so it's not strange to receive a NullReferenceException, but I can't understand this behavior for a nullable type witch is value-type.

    ... another question, How to get type of a reference? one usage may be in a polymorphism object.


    • Edited by zdbdam Wednesday, April 3, 2013 7:39 AM
    Wednesday, April 3, 2013 7:36 AM
  • I believe your solution is good enough.

    MSC on Computer Science (Parallel algorithm)

    • Proposed as answer by SmartWhy Wednesday, April 3, 2013 10:28 AM
    Wednesday, April 3, 2013 7:45 AM
  • You can try this

    using System;
    using System.Reflection;
    using System.Linq.Expressions;
    
    namespace Test
    {
      class Mymemberinfo
      {
        public static int Main()
        {
          decimal? x = null;
          Type xType = GetObjectType(() => x);
          Type genericTypeArgument = GetObjectType(() => x).GetGenericArguments()[0];
          return 0;
        }
        public static Type GetObjectType(Expression<Func<object>> expr)
        {
          var obj =  ((UnaryExpression)expr.Body).Operand;
          return (Type)((PropertyInfo)obj.GetType()
            .GetProperty("Type", BindingFlags.Instance | BindingFlags.Public)).GetValue(obj);
        }
      }
    }

    but your code better.

    • Marked as answer by zdbdam Wednesday, April 3, 2013 11:40 AM
    Wednesday, April 3, 2013 11:02 AM
  • I know, GetType() method, evaluate the object of an instance, not the reference. so it's not strange to receive a NullReferenceException, but I can't understand this behavior for a nullable type witch is value-type.

    It is not a value type. Value types cannot be null.

    This one can. hence it is internally a Reference type that can behave like a Value Type - if it is not null.

    Why would you want to get the type of a Reference at runtime? About the only time those matter is a Compile Time.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2

    Wednesday, April 3, 2013 11:05 AM
  • thanks, It works beautiful!

    I'm a beginner and I don't know anything about Linq or Reflection.

    but thank you anyway, I can come back later when I learned linq :)

    Wednesday, April 3, 2013 11:28 AM
  • I know, GetType() method, evaluate the object of an instance, not the reference. so it's not strange to receive a NullReferenceException, but I can't understand this behavior for a nullable type witch is value-type.

    It is not a value type. Value types cannot be null.

    This one can. hence it is internally a Reference type that can behave like a Value Type - if it is not null.

    Why would you want to get the type of a Reference at runtime? About the only time those matter is a Compile Time.


    Let's talk about MVVM: http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/b1a8bf14-4acd-4d77-9df8-bdb95b02dbe2

    I don't think so, how can nullable<T> be reference-type when it is a struct? (Nullable Structure)

    nullable<T> has a field named "bool HasValue" that indicates it is null or not.

    and that question, I just was curios. you are right, there is no reason to know the type of a reference. :)

    Wednesday, April 3, 2013 11:42 AM
  • It doesn't work at least in .net Framework 4.7.2 it says:

    System.InvalidCastException: Can not cast 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.UnaryExpression'.'

    Looking for a fix ... if I find it I'll post it

    Thursday, July 16, 2020 8:33 PM
  • It doesn't work at least in .net Framework 4.7.2 it says:

    System.InvalidCastException: Can not cast 'System.Linq.Expressions.FieldExpression' to type 'System.Linq.Expressions.UnaryExpression'.'

    Looking for a fix ... if I find it I'll post it

    There is no absolute why to determine this. For a decent discussion see the following

    https://stackoverflow.com/questions/374651/how-to-check-if-an-object-is-nullable


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange

    Thursday, July 16, 2020 10:21 PM