views:

83

answers:

3

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?)}, };

+2  A: 

type? is just syntactic sugar for Nullable<type>.

Knowing this, you can then do something like this:

public Type GetNullableType(Type t)
{
    return typeof(Nullable<>).MakeGenericType(t);
}
ICR
+5  A: 

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)

thecoop
Thanks, this is what I was looking for.
Marc Wittke
+2  A: 

Use a simple generics method:

public Type GetNullable<T>() where T : struct
{
  return typeof(Nullable<T>);
}

This should return the nullable type for any type you pass in.

Rune Grimstad
This was my first idea, but I do not have the `T` at compile time but just an instance of `System.Type`.
Marc Wittke
You do not need T at compile time - thats the wonder of generics.
BeowulfOF