3

What is the difference between

Foo<T> where T : BaseObject

and

Foo<BaseObject>

Isn't this statement the same?

Mat
  • 202,337
  • 40
  • 393
  • 406
MUG4N
  • 19,377
  • 11
  • 56
  • 83
  • possible duplicate of [C# generic "where constraint" with "any generic type" definition?](http://stackoverflow.com/questions/1541152/c-sharp-generic-where-constraint-with-any-generic-type-definition) – Travis J May 13 '12 at 18:56
  • 2
    I don't see where the question is duplicate... – MUG4N May 13 '12 at 18:58

2 Answers2

7

No, it is not the same.

With:

Foo<T> where T : BaseObject

T can be any BaseObject type and its inheritors.

With:

Foo<BaseObject>

T must be BaseObject exactly (assuming no variance modifiers were declared in Foo for the generic type parameter).

Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • If BaseObject is an abstract class, then wont `InheritedObject` work for `Foo` if `InheritedObject : BaseObject`? – Travis J May 13 '12 at 18:57
  • 2
    @TravisJ - No, not unless covariance was declared on the generic type parameter. – Oded May 13 '12 at 18:59
0

Consider this:

var list = new List<object>();
list.Add("Hello");
Console.WriteLine(list[0].Length); // doesn't compile

Similarly, with Foo<BaseObject>, consumers of Foo will only have access to the BaseObject members from Foo's T members. With Foo<T> where T : BaseObject, consumers of Foo will have access to all members of whatever derived type is actually passed for the type argument.

phoog
  • 42,068
  • 6
  • 79
  • 117