Advertisement
stronk_8s

GENERIC INTEFACE

Sep 19th, 2024
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.24 KB | Source Code | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3.  
  4. // Generic interface
  5. interface IRepository<T>
  6. {
  7.     void Add(T item);
  8.     void Remove(T item);
  9.     IEnumerable<T> GetAll();
  10. }
  11.  
  12. // Class implementing the generic interface for a specific type
  13. class Repository<T> : IRepository<T>
  14. {
  15.     private List<T> _items = new List<T>();
  16.  
  17.     public void Add(T item)
  18.     {
  19.         _items.Add(item);
  20.     }
  21.  
  22.     public void Remove(T item)
  23.     {
  24.         _items.Remove(item);
  25.     }
  26.  
  27.     public IEnumerable<T> GetAll()
  28.     {
  29.         return _items;
  30.     }
  31. }
  32.  
  33. class Program
  34. {
  35.     static void Main()
  36.     {
  37.         // Using the generic interface with int
  38.         IRepository<int> intRepository = new Repository<int>();
  39.         intRepository.Add(1);
  40.         intRepository.Add(2);
  41.         foreach (var item in intRepository.GetAll())
  42.         {
  43.             Console.WriteLine($"Integer: {item}");
  44.         }
  45.  
  46.         // Using the generic interface with string
  47.         IRepository<string> stringRepository = new Repository<string>();
  48.         stringRepository.Add("Hello");
  49.         stringRepository.Add("World");
  50.         foreach (var item in stringRepository.GetAll())
  51.         {
  52.             Console.WriteLine($"String: {item}");
  53.         }
  54.     }
  55. }
  56.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement