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?
Enum types cannot be nullable.
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.
On a technical level, there's nothing wrong with using an enum as the type used in a generic type.
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.
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With