Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a generic method allow returning null and accept enum?

How to make the following extension works? I'm binding the ComboBoxe to an enum and in this case it doesn't compile because it returns null.

public static T GetSelectedValue<T>(this ComboBox control)
{
    if (control.SelectedValue == null)
        return null;

    return (T)control.SelectedValue;
}

Note: I want it te return null (instead of default(T)). The question is that what's the where expression that I've got to use?

like image 536
French Boy Avatar asked Sep 04 '11 09:09

French Boy


People also ask

Can enum accept null?

Enum types cannot be nullable.

How do I return a generic null?

So, to return a null or default value from a generic method we can make use default(). default(T) will return the default object of the type which is provided.

Can generic type be enum?

On a technical level, there's nothing wrong with using an enum as the type used in a generic type.

Can generic be void?

Currently, void is not allowed as a generic parameter for a type or a method, what makes it hard in some cases to implement a common logic for a method, that's why we have Task and Task<T> for instance. and use it as a generic parameter for any type or method.


2 Answers

Return a nullable instead of a plain T:

public static T? GetSelectedValue<T>(this ComboBox control) where T : struct
{
    if (control.SelectedValue == null)
        return null;

    return (T)control.SelectedValue;
}
like image 100
Konrad Rudolph Avatar answered Oct 14 '22 05:10

Konrad Rudolph


That's impossible. Value types cannot be null. Your extension method returns an instance of T and if this T is an enum (value type), its value cannot be null. So without changing your return type such method signature simply cannot exist. As far as constraining the generic parameter to be an enum, that's also impossible in C# but possible in MSIL. Jon has blogged about it.

like image 28
Darin Dimitrov Avatar answered Oct 14 '22 05:10

Darin Dimitrov