0

If I want to execute that function it doesn't work.

showdict(RedWineMenu._RedWineMenu);

My classes:

public class RedWine : Wine
{
    public override string Prepare
    {
        get
        {
            return $"Well, {this.Name} wine temperture's same as room temperture. \n All you need to do is pour it into a glass and serve.";
        }
    }
    public override string Name
    {
        get
        {
            return $"{base.Name} ({this.Year})";
        }
    }
}

public class Wine : Drink
{
    public int Year { get; set; }
}

public class Drink : Idrink
{
    public virtual string Name { get; set; }
    
    public virtual string Prepare { get; }

}

This function in the same class as showdict:

private void showdict (Dictionary<int, Drink> dict) 
{
    foreach (var item in dict)
    {
        Console.WriteLine($"{item.Key} - {item.Value.Name}");
    }
}


public class RedWineMenu : Menu
{

    public Dictionary<int, RedWine> _RedWineMenu { get; private set; }



public class Menu
{
    public string KindOfDrink { get; set; }
}

Here you can see the worning

I do'nt get it. If "Drink" is the futher class of RedWine - why can't insert it into that dictionary? How can I do it?

DavidG
  • 113,891
  • 12
  • 217
  • 223
arad
  • 23
  • 4
  • You have one dictionary that is `Dictionary` and one that is `Dictionary`. These are not the same thing. (Inheritance doesn't affect generics the same way. Look up "covariance" and "contravariance".) – Abion47 Mar 16 '21 at 21:10

1 Answers1

0

In C#, the Dictionary<TKey, TValue> type is not covariant meaning you cannot do what you are trying here. However, there is a workaround if you make your showdict generic and using a type constraint, like this:

private void showdict<T>(Dictionary<int, T> dict) 
    where T : Drink
{
    foreach (var item in dict)
    {
        Console.WriteLine($"{item.Key} - {item.Value.Name}");
    }
}
DavidG
  • 113,891
  • 12
  • 217
  • 223
  • What happend in the back of it? Why do I need to add to the name of the function? It does'nt return anything.. It just print it – arad Mar 17 '21 at 07:17
  • I suggest reading about generics in C#, here's a good start https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/ – DavidG Mar 17 '21 at 13:38