Cottleston Pie

Fernando Felman’s thoughts on software development

Variance and Generalized Constraints, MS Research Publications

Posted by Fernando Felman on March 4, 2007

A very good document with recommendation for Variance and Generalized Constraints implementation in C# by Burak Emir, Andrew J. Kennedy, Claudio Russo, and Dachuan Yu.

Let me just quote the Introduction so you can understand what it is all about:

The Generics feature of C# 2.0 introduced parametric polymorphism to the language, supporting type parameterization for types (classes, interfaces, structs,and delegates) and methods (static and instance). Being object-oriented, C# already offers subtype polymorphism, namely the ability for a value of type T to be used in a context that expects type U, if T is a subtype of U.
As it stands, though, subtype and parametric polymorphism interact only through subclassing. In particular, there is no subtyping relationship between distinct instantiations of the same generic type type parameters are said to behave invariantly with respect to subtyping. This leads to a certain inflexibility: a method whose parameter has type IEnumerable<Control>cannot be passed an argument of type IEnumerable<Button>,even though this is safe: since Button is a subclass of Control, something that enumerates Buttons also enumerates Controls. Dually, a method expecting a parameter of type IComparer<Button> cannot be passed an argument of type IComparer<Control>, even though this is safe: something that can compare Controls can also compare Buttons.

The document then details possible extensions to C# in order to express Variance and Generalized Constraints.

I hope MS will implement the recommendations since I already found myself dealing with this issue in the past and I’m not entirely happy with the workaround I used.

Advertisements

One Response to “Variance and Generalized Constraints, MS Research Publications”

  1. […] Variance and Generalized Constraints support for Generics to enable better inheritance options for generics. The nice thing here is the syntax that is dead simple and self-explanatory. […]

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: