7

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?

French Boy
  • 1,471
  • 3
  • 18
  • 23
  • following post answers your question regarding returning null from generic method: http://stackoverflow.com/questions/302096/how-can-i-return-null-from-a-generic-method-in-c – Waqas Sep 04 '11 at 09:40

3 Answers3

8

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;
}
Konrad Rudolph
  • 530,221
  • 131
  • 937
  • 1,214
5

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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • what if he returned default rather than null? – Tim Sep 04 '11 at 09:43
  • @Tim, of course that will work and the correct way to write this extension method but the OP already knows this because he mentioned it in his question. I just tried to explain him that the generic method signature that he is trying to write simply cannot exist. – Darin Dimitrov Sep 04 '11 at 09:44
  • @Darin: Thanks for the answer, in my case, the suggestion that was answered by Konrad useful. – French Boy Sep 04 '11 at 09:47
  • @Darin I just reread OP's question and saw he didn't want to use default. Anyway, I appreciate the answer as I like to understand the "how" of things, not just whether it can or can't be done. – Tim Sep 04 '11 at 09:47
2

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.

Tigran
  • 61,654
  • 8
  • 86
  • 123
  • Yup, it's useful, I think it's OK just by assigning `0` to `None` value and let the extension returns `default(T)` – French Boy Sep 04 '11 at 09:48
  • @French Boy: this is simple and readable, so most natural way of solving that kind of problems. – Tigran Sep 04 '11 at 09:49