Thursday, January 20, 2005

Peek .NET 2005:Gotcha in generics

Connected to my previous blog on generics:
Assume that the Manager class inherits from the Employee class. So the following code is perfectly fine:
Dim mngr as new Manager
Dim emp as Employee=mngr
I can assign a Manager object to the Employee variable since all Managers are Employees.So let's apply a bit of Generics:
dim colMngr as new Collection(Of Manager)
dim colEmp as Collection(Of Employee)=mngr
I am just storing a collection of Managers in a collection of Employees variable. Looks fine? Well it's not...Generics does not work that way.
If the above code is fine then if i have an Executive class inheriting from Employee then colEmp.add(new Executive())
will be legal. But then what if i want to access the collection through the colMngr variable which is supposed to hold only a Collection of Manager objects...but now i have an Executive object inside it.
So the compiler will prevent this from happening. But remember this, as it may seem strange when doing Generics initially

No comments: