Monday 19 May 2014

Minute with Java Vs C# - Type Covariance

It has been a while since I had a look at Java. (I really have a soft spot for Java!).

There are some really good articles on the web about Type Covariance. In a nutshell this is the ability to preserve/use a specific derived type in place of a general type.

Consider the following Java example. (Compiled with JDK 1.7).

I like the type covariance here. Even tough the "CanDoSomeWork" interface expects "SomeWork", the actual implementation allows a derived type of "SomeWork". In the following context, the type "Cat".


From the consumers point of view, there is no need for casting.


However if you try this in C# you will get the following.

Type Covariance in C# Vs Java 1.7 (7)



I think what Java compiler has done here is pretty cool, and neat. However I have some doubts.

Normally in a larger/enterprise scale application, IoC containers are used. It is the responsibility of the IoC container to create instances and manage their life-styles. Since the code is normally developed against an abstraction (e.g. interface), the consumer always expects the generalised type (think LSP).

 I am not sure how to use this feature really... may be its my lack of imagination or misunderstanding. :-(

1 comment:

  1. Thanks for sharing such informative guide on .Net technology. This post gives me detailed information about the .net technology. I am working as trainer in leading




    Dot Net Training in Chennai | Dot Net Training in anna nagar | Dot Net Training in omr | Dot Net Training in porur | Dot Net Training in tambaram | Dot Net Training in velachery





    ReplyDelete