-1

I'm essentially trying to upcast an object but I don't know how to deal with the generics. Below is a super-contrived example but it illustrated a situation I'm working with. Perhaps I need an implicit operator but I'm not sure what that would look like in this scenario.

using System;
using System.Collections.Generic;

class MainClass {
  public static void Main (string[] args) {

    var cats = new Dictionary<string, IAnimal<ICat>>()
    {
      { "paws", new Tabby() },
      { "teeth", new MountainLion() }
    };

    foreach (var cat in cats)
    {
      cat.Value.talk();
    }
  }

  public interface IAnimal<T> where T : ICat
  {
    void talk();
  }

  public interface ICat
  {
  }

  public class HouseCat : ICat
  {
  }

  public class BigCat : ICat
  {
  }

  public class MountainLion : IAnimal<BigCat>
  {
    public void talk() {
      Console.WriteLine("Rawr!");
    }
  }

  public class Tabby : IAnimal<HouseCat>
  {
    public void talk() {
      Console.WriteLine("Meow");
    }
  }

}
Austin
  • 576
  • 2
  • 8
  • 21
  • You need to use the `out` generic modif ([docs](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/out-generic-modifier)). Use it like this: `public interface Animal` – Kalten Dec 29 '20 at 17:41
  • 2
    Interfaces should really be prepended with an I in their name... – xanatos Dec 29 '20 at 17:41
  • and as written by kalten, you need covariance (https://stackoverflow.com/questions/2719954/understanding-covariant-and-contravariant-interfaces-in-c-sharp) that is only possible with interfaces (and fortunately `Animal` is an interface) – xanatos Dec 29 '20 at 17:42
  • I added the "I" before interfaces. – Austin Jan 04 '21 at 18:07

1 Answers1

0

Thanks to @kalten I arrived at this solution:

public interface Animal<out T> where T : Cat

You can see it working here: https://repl.it/@austinrr/FlippantLonelyTab#main.cs

Austin
  • 576
  • 2
  • 8
  • 21