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. :-(

Monday, 12 May 2014

Notes around .NET threading, use of timers etc

I was listening to Jeffrey Richter and he mentioned the how widespread the incorrect use of .NET threads. There is no point reinventing the wheel, simply have a look at the following code. It looks very harmless, however it is a course for real concern.


The comments in the code speak for itself. However is this "better" than using "Thread.Sleep" to pause a thread... :-)