-3

I wonder what is this? This kind of a generic method I think. It has a part with 'where'. What about that? There is also generic classes I've heard. How can I learn these can you recommend an article?

    protected T Item<T>() where T : class
    {
        return GetDataItem() as T ?? default(T);
    }
Serhat Koroglu
  • 1,263
  • 4
  • 19
  • 41

1 Answers1

5

The where clause is called a "generic constraint". In that case, where T: class dictates that T must be a reference type (i.e., not a struct).

More info on generic constraints: http://msdn.microsoft.com/en-us/library/d5x73970.aspx And generic classes: http://msdn.microsoft.com/en-us/library/sz6zd40f.aspx

Edit

In the snippet you provided, the constraint is needed because otherwise the null-coalescing operator (??) wouldn't make sense, since value types (structs) can't be null.

dcastro
  • 66,540
  • 21
  • 145
  • 155
  • 2
    minor footnote re your last line: `Nullable` (for any `T : struct`) is itself a `struct` and can notionally be `null` – Marc Gravell Sep 04 '13 at 08:38
  • Thanks for the correction. Isn't it weird that neither `T:struct` nor `T:class` allow `T` to be a Nullable? – dcastro Sep 04 '13 at 08:48