The difference between Foo <T>, where T: BaseObject and Foo <BaseObject>

What's the difference between

Foo<T> where T : BaseObject

and

Foo<BaseObject>

Does this statement not coincide?

+3
source share
2 answers

No, this is not the same.

WITH

Foo<T> where T : BaseObject

Tcan be any type BaseObjectand its heirs.

WITH

Foo<BaseObject>

Tmust be BaseObjectexactly (provided that variance modifiers have not been declared in Foofor a type parameter).

+7
source

Consider this:

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

Similarly, with Foo<BaseObject>, Foo users will only have access to BaseObject elements from Foo members T. With Foo<T> where T : BaseObject, Foo users will have access to all members of any derived type actually passed for the type argument.

0
source

All Articles