I am thankful for Mitsu Furuta’s Presentation about generics, and then for his answers to my question in his blog.
Acutely i am always happy to follow Mitsu’s presentation. He is always very accurate, each word he puts on his PPT is important, and has a meaning, a very important one!
The presentation i am talking about was about C# 2.0 , on of the things he discussed was generics ,and one of the slides had two extremely important sentences : be careful with methods overloads, and dont forget about Object orientation.
Problem:
Reading this i remembered the issue i got in C# in generic collections. specifically in IDictionary, my problems with this class were the following:
1: Dictionary implements IDictionary and the non generic IDictionary.
so u can make something like
IDictionary d=new Dictionary;
then cast it like this
IDictionary d1=(IDictionary)d;
so inserting here any object in the IDictionary will throw a runtime exception, and no compile time check is done! (Â see why is it done like this below)
2:using the operator [] on the first instance (the generic one) with a key that doesnt exist will throw an exception, whereas doing the same with the no generic one will just return null!
int i=d1k] throws exception if k doesnt exist
object o=d1[k]Â return null if k doesnt exist
so imagine having IDictionary , isnt the signature of the [] operator identical with the one of the non generic IDictionary?
then i told myself “what a bizarre compiler!”.
so i told my self (whats the! two different behavior for the same method in the same class??? how come!)
Explantation:
in the case number 1, Mitsu cleared it out for me! DONT FORGET OBJECT ORIENTATION! Deferent type of a generic task has nothing in common, they just look the same, but there is no inheritance, no polymorphism, so YES , you need to implement the same interface, to be able to call polymorphically the methods of that interface!
and about the two behavior of the [] operator in IDictionary and IDictionary, YES they can have the same signature BUT THIS IS EXPLICITE INHERITANCE!
explicit inheritance is a feature in C# where u can implement the same method , differently for different classes, by using InterfaceName.Method();
i didnt know this feature before, the two methods live in different scopes in the class, so there is no overloading.
but anyway, u should be careful about generics, any static field or method is static per closed type and not per generic class.
and also be careful about overloading, especially after closing the class with the type.
thanks mitsu! :)