[Mono-list] Crazy generic dictionary?

Robert Jordan robertj at gmx.net
Sun Sep 30 15:38:53 EDT 2007


Robert Jordan wrote:
> Andrés G. Aragoneses [ knocte ] wrote:
>> Robert Jordan escribió:
>>> Andrés G. Aragoneses [ knocte ] wrote:
>>>> Robert Jordan escribió:
>>>>> Andrés G. Aragoneses [ knocte ] wrote:
>>>>>> Today I've come out with this wish:
>>>>>>
>>>>>> Dictionary<typeof(T), List<T>> InternalCollection;
>>>>>>
>>>>>>
>>>>>> Of course, the compiler tells me an error, but I would want to know if I 
>>>>>> can make this kind of collection with C# generics, in order to obtain 
>>>>>> syntatic sugar and type safety, I mean:
>>>>>>
>>>>>> //compilation should succeed only if oMyObj is TypeX:T
>>>>>> InternalCollection.Add(typeof(TypeX), oMyObj);
>>>>>>
>>>>>> Any thoughts?
>>>>> class FooDictionary<T> : Dictionary<System.Type, T>
>>>>> {
>>>>> 	public void Add (T t)
>>>>> 	{
>>>>> 		this [typeof(T)] = t;
>>>>> 	}
>>>>> }
>>>>>
>>>> But that would only allow adding one object:
>>> Well, then use that slightly modified Add method:
>>>
>>>   	public void Add (T t)
>>>   	{
>>> 		if (t == null)
>>> 			throw new ArgumentNullException ("t");
>>> 		this [t.GetType ()] = t;
>>>   	}
>>>
>> Ok! But if I modify it to use lists, I get a compiler error:
>>
>> class FooDictionary<T> : Dictionary<Type, List<T>>
>> {
>>      public void Add (List<T> t)
>>      {
>>          if (t == null)
>>          {
>>              throw new ArgumentNullException("t");
>>          }
>>          if (t.Count > 0)
>>          {
>>              this[t[0].GetType()] = t;
>>          }
>>      }
>> }
>>
>> ...
>>
>> FooDictionary<mytype> foo = new FooDictionary<mytype>();
>> foo.Add(new List<subtypeA>());
>>
>> Error	11	Argument '1': cannot convert from 
>> 'System.Collections.Generic.List<subtypeA>' to 
>> 'System.Collections.Generic.List<mytype>'
>>
>> However, it should allow it because subtypeA inherits from mytype, 
>> right? I think I've reached a limitation of .NET generics, which I think 
>> I read about here[1] :(
> 
> This works, at least with MS.NET 2.0 csc:
> 
> using System;
> using System.Collections.Generic;
> 
> class FooDictionary<T> : Dictionary<System.Type, List<T>>
> {
> 	public void Add (List<T> t)
> 	{
> 		if (t == null)
> 			throw new ArgumentNullException ("t");
> 		// key is the generic argument of List<T>
> 		this [t.GetType ().GetGenericArguments() [0]] = t;
> 	}
> }
> 
> class Test
> {
> 	static void Main ()
> 	{
> 		FooDictionary<int> d = new FooDictionary<int> ();
> 		d.Add (new List<int> ());
> 	}
> }

Scratch this. I didn't notice that you were using subclasses.

Robert



More information about the Mono-list mailing list