Guest User

Untitled

a guest
Oct 26th, 2023
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.20 KB | None | 0 0
  1.     public interface IRepository<out T>
  2.     {
  3.         T Get();
  4.     }
  5.  
  6.     public interface IContravariantRepository<in T>
  7.     {
  8.         void Add(T item);
  9.     }
  10.  
  11.     public class Animal
  12.     {
  13.         public string Name { get; set; }
  14.     }
  15.  
  16.     public class Dog : Animal
  17.     {
  18.         public string Breed { get; set; }
  19.     }
  20.  
  21.     public class AnimalRepository : IRepository<Animal>, IContravariantRepository<Animal>
  22.     {
  23.         public Animal Get()
  24.         {
  25.             Console.WriteLine("Getting an animal from the repository.");
  26.             return new Animal { Name = "Fido" };
  27.         }
  28.  
  29.         public void Add(Animal item)
  30.         {
  31.             Console.WriteLine("Adding an animal to the repository.");
  32.         }
  33.     }
  34.  
  35.     public class DogRepository : IRepository<Dog>, IContravariantRepository<Dog>
  36.     {
  37.         public void Add(Dog item)
  38.         {
  39.             Console.WriteLine("Adding an animal to the repository.");
  40.         }
  41.  
  42.         public Dog Get()
  43.         {
  44.             Console.WriteLine("Getting a dog from the repository.");
  45.             return new Dog { Name = "Buddy", Breed = "Golden Retriever" };
  46.         }
  47.     }
  48.  
  49.     internal class Program
  50.     {
  51.         public static void UseAnimalRepository(IRepository<Animal> repository)
  52.         {
  53.             var animal = repository.Get();
  54.             Console.WriteLine("Used repository to get an animal: " + animal.Name);
  55.         }
  56.  
  57.         public static void UseDogRepository(IContravariantRepository<Dog> repository)
  58.         {
  59.             repository.Add(new Dog { Name = "Spot", Breed = "Dalmatian" });
  60.             Console.WriteLine("Used repository to add a dog.");
  61.         }
  62.  
  63.         public static void Main()
  64.         {
  65.             AnimalRepository animalRepository = new AnimalRepository();
  66.             DogRepository dogRepository = new DogRepository();
  67.  
  68.             Console.WriteLine("Using Animal Repository:");
  69.             UseAnimalRepository(animalRepository);
  70.  
  71.             Console.WriteLine("\nUsing Dog Repository:");
  72.             UseAnimalRepository(dogRepository);
  73.  
  74.             Console.WriteLine("\nUsing Dog Repository (Contravariance):");
  75.             UseDogRepository(dogRepository);
  76.         }
  77.     }
Advertisement
Add Comment
Please, Sign In to add comment