0
0
C Sharp (C#)programming~30 mins

Contravariance with in keyword in C Sharp (C#) - Mini Project: Build & Apply

Choose your learning style9 modes available
Contravariance with in keyword
📖 Scenario: Imagine you are building a simple animal sound system. You want to create a way to make animals produce sounds, but you want to allow flexibility in the types of animals your system can handle.
🎯 Goal: Build a small C# program that demonstrates contravariance using the in keyword in interfaces. You will create an interface with contravariant type parameter, implement it for different animal types, and show how contravariance allows assigning a more general interface to a more specific one.
📋 What You'll Learn
Create an interface called ISoundMaker<in T> with a method MakeSound(T animal).
Create two classes: Animal and Dog, where Dog inherits from Animal.
Implement ISoundMaker<Animal> in a class called AnimalSoundMaker.
Show that an ISoundMaker<Animal> can be assigned to an ISoundMaker<Dog> variable because of contravariance.
Call the MakeSound method on the ISoundMaker<Dog> variable with a Dog instance.
💡 Why This Matters
🌍 Real World
Contravariance allows flexible and reusable code when working with collections or handlers that accept more general types but are used with more specific types.
💼 Career
Understanding contravariance is important for designing clean APIs and working with delegates, events, and generic interfaces in professional C# development.
Progress0 / 4 steps
1
Create the Animal and Dog classes
Create a class called Animal with a public string property Name. Then create a class called Dog that inherits from Animal.
C Sharp (C#)
Need a hint?

Use public class Animal and add a public string Name { get; set; } property. Then create public class Dog : Animal.

2
Create the contravariant interface ISoundMaker
Create an interface called ISoundMaker<in T> with a method void MakeSound(T animal).
C Sharp (C#)
Need a hint?

Use interface ISoundMaker<in T> and add the method void MakeSound(T animal);.

3
Implement ISoundMaker<Animal> in AnimalSoundMaker
Create a class called AnimalSoundMaker that implements ISoundMaker<Animal>. Implement the MakeSound method to print $"{animal.Name} makes a sound.".
C Sharp (C#)
Need a hint?

Create AnimalSoundMaker implementing ISoundMaker<Animal>. Inside MakeSound, use Console.WriteLine($"{animal.Name} makes a sound.");.

4
Demonstrate contravariance with in keyword
In the Main method, create an ISoundMaker<Animal> variable called animalSoundMaker and assign it a new AnimalSoundMaker(). Then create an ISoundMaker<Dog> variable called dogSoundMaker and assign animalSoundMaker to it. Finally, call dogSoundMaker.MakeSound with a new Dog named "Buddy".
C Sharp (C#)
Need a hint?

Assign animalSoundMaker to dogSoundMaker because of contravariance. Then call dogSoundMaker.MakeSound(new Dog { Name = "Buddy" }).