user3591682
user3591682

Reputation:

Create a nullable type dynamically

I need to set the Type variable to be a nullable one. e.g.

public Type CreateNullable(Type type){
    if (type.IsValueType)
        return Nullable<type>;

    // Is already nullable
    return type;
}

I'm seeing as there are a finite amount of the ValueType, I figure I'll just create a Dictionary of all the value types as nullable, and the return that. But am keen to see if there's a smarter way.

Upvotes: 3

Views: 1510

Answers (2)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

Answer provided by Cory looks fine, but I would add check to make sure type is not already Nullable<T>:

public Type CreateNullable(Type type){
    if (type.IsValueType && (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Nullable<>)))
        return typeof(Nullable<>).MakeGenericType(type);

    // Is already nullable
    return type;
}

Upvotes: 5

Cory Nelson
Cory Nelson

Reputation: 29981

public Type CreateNullable(Type type){
    if (type.IsValueType)
        return typeof(Nullable<>).MakeGenericType(type);

    // Is already nullable
    return type;
}

Upvotes: 9

Related Questions