Visual Studio 2010: Delegates, Generic IEnumerable
This is kind of a re-blog. My goal is to have a more specific blog than before.
Generic Delegates
Let’s warm up with some generic delegates to start getting used to some of the code. Lines 23 to 26 we build a collection of delegate functions that we later loop through and execute.
The point here is the curr_instance() will call all 3 methods: delegateList is essentially an array of refererences to methods: |
Sample Code: Building a data model to experiment with
We need to define some basic patterns to illustrate our points.
|
Challenges: How type safety is enforced in VS 2010
The scenario we are trying understand well is that we want generics to wok with the same we get concrete types to work. Let's start with the concrete types. Suppose you have 2 classes as follows: This has always been legal in C# 3.0 But this is not legal
However when dealing with generics, in spite of what your intuition would tell you, this is not legal:
This is needed because we don't know if we are going to add a "SubContractor," which might also be derived class of a person. Imagine a scenario where you have an array like this: Imagine loop through this array and trying to access the "Salary." Everything works fine until you get to the "SubContractor," where "Hours" and "HourlyRate" are the data elements. We'd get a crash. That is what the type system is protecting us from. |
|
Comments
Anonymous
July 23, 2009
I disagree completely with your conclusion, and here's why: The example you give is looping over a collection of Person looking for a Salary property. If the Salary property is not part of the base class Person and only part of the subclass Employee, then the compiler error should be that the base class Person does not have a Salary field. The last compiler error in your post is, in fact, a lie from the compiler, and the only reason a compiler would lie is if it has a bug. Since converting an Employee to a Person is always legal, then we are guaranteed that converting a List<Employee> to an IList<Person> is always safe, and any claim by the compiler that it might not be safe is factually incorrect. Obviously, since our variables are now declared as type Person and not as type Employee, we only have access to those members which are included in the base class, which is exactly what happens when we perform the same cast on a single item. That, therefore, is the final proof of a compiler bug, handling an identical situation differently just because we happen to be inside a generic collection.Anonymous
July 23, 2009
Hey, this blog template is badly messed up in firefox.Anonymous
July 24, 2009
Will respond to both issues very soon.