How to make a general method to allow null returns and accept an enumeration?

How to make the next extension? I bind a ComboBoxe to an enumeration, in which case it does not 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 to return null (instead of the default value (T)). The question is, where is the expression that I should use?

+6
source share
3 answers

We return nullable instead of a simple T :

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

It's impossible. Value types cannot be null. Your extension method returns an instance of T , and if this T is an enumeration (value type), its value cannot be null. Thus, without changing the return type, such a method signature simply cannot exist. Regarding the limitation of the general parameter on the enumeration, which is also impossible in C #, but possible in MSIL. Jon has a blog about it .

+5
source

The most common approach in this case applies to all other members of your enumeration: define None , in this case, in your logic, None == null .

+1
source

Source: https://habr.com/ru/post/896579/


All Articles