What is the difference between
Foo<T> where T : BaseObject
and
Foo<BaseObject>
Isn't this statement the same?
What is the difference between
Foo<T> where T : BaseObject
and
Foo<BaseObject>
Isn't this statement the same?
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).
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.