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 wher开发者_运维技巧e expression that I've got to use?
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.
The most common approach in this case is among all other members of your enumeration define None
, in that case in your logic None
==null
.
精彩评论