Nullable type testing against null
I need to test if a Nullable<T> instance is null after it's been converted to an object. My current code fails using this:
| | using System; using System.Collections.Generic; using System.Text;namespace TestNullable { class Program { staticvoid Main(string[] args ) { System.Nullable<int> n =null; object o = n; if( o ==null ) { Console.WriteLine( "IsNull" ); } else { Console.WriteLine( "NotNull" ); } } } }
|
What's best way to handle this considering I don't know what T is in advance of testing for null.Regards
Lee
This is not a bug.
Even though you are assigning null to 'n', n still contains a Nullable<T> structure.
So when you assign 'n' to an object, you are actually boxing a Nullable structure and pointing 'o' to the boxed version. So when you compare this boxed version with null, you are saying 'is null equal to this object with something' and hence why this returns false.
Oh just another thing, to convert a Nullable type to an object, so that comparision to null will work, use the following:
| | System.Nullable<int> n = null;object o = Nullable.ToObject(n);
|
ToObject will return null if 'n' doesn't have a value, otherwise it returns its value.
Also, in C#, there is shorthand for using Nullable<T>:
Thanks for your replies but my problem is a little more complicated than the original post made out. I am actually using reflection to pull values out of an object. I am testing for null but PropertyInfo.GetValue and FieldInfo.GetObject return a boxed version of Nullable<T> which causes me problems. I want to know if there is an *easy* way of finding out this. The following is an updated example:
| | using System; using System.Reflection; using System.Collections.Generic; using System.Text; namespace TestNullable { class Program { public class TestNull { public Nullable<int> SomeInt = null; } static void Main( string[] args ) { TestNull testNull = new TestNull(); FieldInfo fi = testNull.GetType().GetField( "SomeInt" ); object o = fi.GetValue( testNull ); if( o == null ) { Console.WriteLine( "IsNull" ); } else { Console.WriteLine( "NotNull" ); } } } } |
I figure I could drill into the type and find out if it's Nullable<T> and then call Nullable.ToObject on it...
Regards Lee
I had to do something similar to this. First determine if the type is nullable or not. If it is then cast to a nullable type. However, I do not convert to object with ToObject. Why should I? There is a property on the nullable type HasValue() which tells you what you want to know. ToObject scares me, as it most likely is just the boxed value type.