Search code examples
c#reflectiontypesnullable

Smart way to find the corresponding nullable type?


How could I avoid this dictionary (or create it dynamically)?

Dictionary<Type,Type> CorrespondingNullableType = new Dictionary<Type, Type>
{
    { typeof(bool),    typeof(bool?) },
    { typeof(byte),    typeof(byte?) },
    { typeof(sbyte),   typeof(sbyte?) },
    { typeof(char),    typeof(char?) },
    { typeof(decimal), typeof(decimal?) },
    { typeof(double),  typeof(double?) },
    { typeof(float),   typeof(float?) },
    { typeof(int),     typeof(int?) },
    { typeof(uint),    typeof(uint?) },
    { typeof(long),    typeof(long?) },
    { typeof(ulong),   typeof(ulong?) },
    { typeof(short),   typeof(short?) },
    { typeof(ushort),  typeof(ushort?) },
    { typeof(Guid),    typeof(Guid?) },
};

Solution

  • You want to do something like:

    Type structType = typeof(int);    // or whatever type you need
    Type nullableType = typeof(Nullable<>).MakeGenericType(structType);
    

    To get the corresponding Nullable<T> for a given T (in this example, int)