C# Generics Not So Generic
I was working on small library project and I wanted to maintain as much flexibility as possible and therefore came up with something like this:
But, alas, the compiler complains and all kinds of little tweaks didn't work either. In the end it turns out that C# doesn't like variance in generic types (see MSDN), I originally thought this would work with interfaces but no dice.
The solution to this kind issue is kind of the kind of thing that makes me crazy; that is, add more code because the compiler isn't cleaver enough to do the right thing.
public class Foo
{
public void DoSomething(IEnumerable<KeyValuePair<string, IList<string>>> arg)
{ }
}
public class Bar
{
public void Method()
{
Dictionary<string, List<string>> d = new Dictionary<string, List<string>>();
Foo f = new Foo();
f.DoSomething(d);
}
}
But, alas, the compiler complains and all kinds of little tweaks didn't work either. In the end it turns out that C# doesn't like variance in generic types (see MSDN), I originally thought this would work with interfaces but no dice.
The solution to this kind issue is kind of the kind of thing that makes me crazy; that is, add more code because the compiler isn't cleaver enough to do the right thing.
public class Foo
{
public void DoSomething(FooMethodWrapper arg) { }
}
public interface IWrapper
{
IEnumerable<string> Keys { get; }
IList<string> this[string key] { get; }
}
public class FooMethodWrapper : IWrapper
{
Dictionary<string, List<string>> m_d;
public FooMethodWrapper(Dictionary<string, List<string>> d)
{ m_d = d; }
public IEnumerable<string> Keys { get { return m_d.Keys; } }
public IList<string> this[string key] { get { return m_d[key]; } }
}
public class Example
{
public void Method()
{
Foo f = new Foo();
f.DoSomething(new FooMethodWrapper(d));
}
}
There are no comments.