Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a nullable type dynamically

Tags:

c#

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.


1 Answers

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

    // Is already nullable
    return type;
}
like image 145
Cory Nelson Avatar answered Dec 19 '25 14:12

Cory Nelson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!