Actually, the code shown, which can be shortened to:
void f(object x)
{
List<Something<More<T,S>,U>> lst = (List<Something<More<T,S>,U>>)x;
foreach (Something<More<T,S>,U> elem in lst) { ... }
}
will behave very badly if you try to use derivation as a typedef. The
cast
would fail. The foreach would return no results. etc.
You should post a concise-but-complete code example that unambiguously
demonstrates what you're talking about. As it is, your comment is too
vague for me to make sense of it. I don't doubt what you wrote is true,
but without enough context it's impossible to know for sure why, never
mind why it should relate to this particular discussion.
It is true that pre-C# 4.0, lack of variance between generic types would
interfere with casting between generics that don't have exactly the same
type parameters. But a) that doesn't really apply to this particular
discussion (we're dealing with concrete types made from generics...no type
parameter variance needed), and b) in C# 4.0 support for variance will
help address a lot of the concerns related to variance anyway.
See below for a concise-but-complete code example that demonstrates use of
Scott's suggestion (i.e. inheritance as a way of typedef-ing). No compile
or run-time errors involved.
Pete
using System;
using System.Collections.Generic;
namespace TestCastTypedefInherit
{
class Program
{
class MyList : List<KeyValuePair<string, string>>
{
}
static void Main(string[] args)
{
MyList list = new MyList();
list.Add(new KeyValuePair<string, string>("key1", "value1"));
list.Add(new KeyValuePair<string, string>("key2", "value2"));
list.Add(new KeyValuePair<string, string>("key3", "value3"));
object obj = list;
List<KeyValuePair<string, string>> list2 =
(List<KeyValuePair<string, string>>)obj;
foreach (KeyValuePair<string, string> kvp in list2)
{
Console.WriteLine(kvp.Key + ", " + kvp.Value);
}
Console.ReadLine();
}
}
}