Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generic Dictionary with a value as a Interface with a Generic reference

Tags:

c#

.net

generics

I want to have a Dictionary where the values are generic objects and will not be the same for each value int he dictionary. How can this be done, I feel like I am missing something simple.

EG


    public interface IMyMainInterface
    {
        Dictionary<string, IMyInterface<T>> Parameters { get; }
    }

    public interface IMyInterface<T>
    {
        T Value
        {
            get;
            set;
        }

        void SomeFunction();
    }

Result:
dic.Add("key1", new MyVal<string>());
dic.Add("key2", new MyVal<int>());

like image 764
Sytone Avatar asked Jan 22 '23 04:01

Sytone


1 Answers

You can't do that because T has no meaning in IMyMainInterface. If your aim is for each value to be an implementation of some IMyInterface<T> but each value could be an implementation for a different T, then you should probably declare a base interface:

public interface IMyInterface
{
    void SomeFunction();
}

public interface IMyInterface<T> : IMyInterface
{
    T Value { get; set; }
}

then:

public interface IMyMainInterface
{
    Dictionary<string, IMyInterface> Parameters { get; }
}

EDIT: Given your updated question, it looks like this is what you're trying to do. If you want to know why you have to do this, think about how you would try to use the values in the dictionary if you were able to use your original code. Imagine:

var pair = dictionary.First();
var value = pair.Value;

What would type could value be inferred as?


If, however, each value should be of the same T, then you just need to make your other interface generic too. To make it clearer, I've renamed the type parameter to keep the Ts separate:

public interface IMyMainInterface<TFoo>
{
    Dictionary<string, IMyInterface<TFoo>> Parameters { get; }
}
like image 55
Jon Skeet Avatar answered May 14 '23 01:05

Jon Skeet