0

I have an interface that looks like this

 public interface SomeInterface<T, U>
    where T : struct
    where U : class
{
    void Method1();
    IDictionary<T, BaseClassItem<U>> GetDictionary();
}

I have one of the implementations like this

public class LruEvictor<T, U> : SomeInterface<T, U>
    where T : struct
    where U : class
{
    private Dictionary<T, BaseClassItem<U>> _dictionary;

    public void Evict()
    {

    }
    public IDictionary<T, BaseClassItem<U>> GetDictionary()
    {
        _dictionary = new Dictionary<T, BaseClassItem<U>>();
        return _dictionary;
    }

}

In the above GetDictionary() method I would like to return a dictionary of type Dictionary<T, DerivedItem<U>>.

Is that possible? If yes how do I do it.

Given below is the derived class implementation.

public class DerivedItem<U> : BaseClassItem<U>
    where U : class
{        

    public DerivedItem(U value) :base(value)
    {

    }
    public DateTime LastAccessed { get; private set; }

    public override void OnAccessed()
    {
        LastAccessed = DateTime.Now;
    }
}

Any input will be appreciated.

Thanks in advance.

IamaC
  • 357
  • 1
  • 10
  • 23
  • possible duplicate of [covariance in c#](http://stackoverflow.com/questions/4038125/covariance-in-c-sharp) – Euphoric Jul 10 '14 at 06:49

2 Answers2

2

I'm fairly sure you can't do this, as it would break the type system.

Consider the usual animal example:

public IDictionary<T, Animal> GetDictionary()
{
    _dictionary = new Dictionary<T, Llama>();
    return _dictionary; // Imagine you can do this
}

IDictionary<T, Animal> dict = GetDictionary();
dict.Add(MakeT(), new Horse()); // Ouch.
T.C.
  • 133,968
  • 17
  • 288
  • 421
1

No, you can't do that. A simple version of your question would be that given

class Base { }
class Derived : Base { }

is it possible to use IDictionary<T, Base> dict = new Dictionary<T, Derived>().

This is not possible because covariance rules of C# don't allow that. And for good reason because if it would work then you could simply add an object of type Base to the dictionary that should only accept Derived objects.

Dirk
  • 10,668
  • 2
  • 35
  • 49
  • Thanks @ Dirk. T.C and you helped me understand better. I have accepted T.C's answer since it came first. – IamaC Jul 10 '14 at 14:12