|
dev
newsgroups
|
|||||||||||||||||||||||
|
|||||||||||||||||||||||
Reflection and NullableCan someone please kindly show me how to determine if a type (read value type) is Nullable. MSDN has this KB: How to: Identify a Nullable Type (C# Programming Guide) http://msdn2.microsoft.com/en-us/library/ms366789.aspx however, using their code snippet, I couldn't get it to work: public class MyClass { public static void Main() { Nullable<int> j = new Nullable<int>(20); Type type = j.GetType(); if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>)) { Console.WriteLine("j is Nullable"); } else Console.WriteLine("j is NOT Nullable"); Console.WriteLine("Type of j is {0}", j.GetType()); } } The Output I got is: j is NOT Nullable Type of j is System.Int32 thus, is there no way to determine a nullable or an non-nullable value types? Thanks for your help in advanced. "Joe Bloggs" <es***@rocketmail.com> wrote: I answered in your multipost in dotnet.general.> Can someone please kindly show me how to determine if a type (read > value > type) is Nullable. -- Barry Joe Bloggs <es***@rocketmail.com> wrote:
> Can someone please kindly show me how to determine if a type (read Finding out if a type is nullable is fine, but you can't find out from > value type) is Nullable. a value in the way you're doing. This is because calling GetType() involves boxing the nullable value. Now, from the C# spec: <quote> A boxing conversion from a nullable type T? is processed as follows: * If the source value is null (HasValue property is false), the result is a null reference of the target type. * Otherwise, the result is a reference to a boxed T produced by unwrapping and boxing the source value. </quote> In other words, by the time you call GetType(), you're either calling it on null (resulting in an exception) or on the boxed non-nullable value type. Now, do you actually need it from a Type object? If so, the test you showed works fine. (Try it with typeof(Nullable<int>).) -- Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet If replying to the group, please do not mail me too
Other interesting topics
Connection timeout when using transactions
Conversion from 1.1 to 2.0 and Warnings Detecting if a NTAccount is user or a group Accessing a dll in the GAC TLB using problem Debug conditional code in class that implements an interface... does it work? Which operating System on Development client? Upgrading to later version of .NET Framework 2.0 Fixed String Size. Current naming convention of abstract classes - BaseFoo vs. FooBase? |
|||||||||||||||||||||||