Note that there are some explanatory texts on larger screens.

plurals
  1. POC# Generics: wildcards
    primarykey
    data
    text
    <p>I'm new to the c# world, and I'm trying to wrap my head around generics. Here is my current problem:</p> <pre><code>public Interface IAnimal{ string getType(); } public Interface IAnimalGroomer&lt;T&gt; where T:IAnimal{ void groom(T); } </code></pre> <p>Now I want to have a dictionary that contains these animal groomers. How do I do that? In java, I could do something like this:</p> <pre><code>HashMap&lt;String,IAnimalGroomer&lt;?&gt;&gt; groomers = new HashMap&lt;&gt;(); </code></pre> <p>Edit: Here is an example of what I'm trying to do:</p> <pre><code>public class Dog : IAnimal { public string GetType() { return "DOG"; } public void ClipNails() { } } public class DogGroomer : IAnimalGroomer&lt;Dog&gt; { public void Groom(Dog dog) { dog.ClipNails(); } } public class Program { private List&lt;IAnimalGroomer&lt;IAnimal&gt;&gt; groomers = new List&lt;IAnimalGroomer&lt;IAnimal&gt;&gt;(); public void doSomething() { //THIS DOESN"T COMPILE!!!! groomers.Add(new DogGroomer()); } } </code></pre> <p><strong>EDIT</strong> I think my intentions were unclear in the original post. My ultimate goal is to make an AnimalGroomerClinic that employs different types of IAnimalGroomers. Then animal owners can drop off animals at the clinic, and the clinic can decide which groomer should take care of the animal:</p> <pre><code>public class AnimalGroomerClinic { public Dictionary&lt;String, IAnimalGroomer&gt; animalGroomers = new Dictionary&lt;String,IAnimalGroomer&gt;(); public void employGroomer(IAnimalGroomer groomer){ animalGroomers.add(groomer.getAnimalType(), groomer); } public void Groom(IAnimal animal){ animalGroomers[animal.getAnimalType()].Groom(animal); } } </code></pre> <p>I realize I could do this without using generics. But the generics allow me to write the <code>IAnimalGroomer</code> interface in such a way that it is tied (at compile time) to a specific instance of <code>IAnimal</code>. In addition, concrete classes of <code>IAnimalGroomer</code> don't need to cast their <code>IAnimals</code> all the time, since generics would force implementations to deal with one specific kind of animal. I have used this idiom before in Java, and I'm just wondering if there is a similar way to write it in C#.</p> <p><strong>Edit 2:</strong> Lots of interesting discussion. I'm accepting an answer that pointed me to dynamic dispatching in the comments. </p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload