Advertisement
bero_0401

Generics & Enumerable

Oct 3rd, 2024
34
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.52 KB | Source Code | 0 0
  1. using revision;
  2. using System.Collections;
  3. using System.Numerics;
  4.  
  5. public class Program
  6. {
  7.  
  8.  
  9.     static  void Main(String[] args)
  10.     {
  11.  
  12.        // var genList = new GenericList<Person>();
  13.        // genList.add(new Person(1 , "Abeer" , "012" , "Damietta" ));
  14.  
  15.         var genList = new List<string>();
  16.  
  17.         genList.Add("Abeer");
  18.         genList.Add("Sara");
  19.         genList.Add("Malak");
  20.  
  21.         foreach (var item in genList)
  22.         {
  23.             Console.WriteLine(item);
  24.         }
  25.  
  26.  
  27.         Console.WriteLine(Add(3 , 2));
  28.         Console.WriteLine(Add(3.4 , 5));
  29.       //  Console.WriteLine(Add(3 , "string")); xxx
  30.     }
  31.  
  32.  
  33.     static T Add<T>(T num1, T num2) where T : INumber<T>
  34.     {
  35.         return num1 + num2;
  36.     }
  37.  
  38.  
  39.  
  40.     public class GenericList<T> :IEnumerable<T> where T : class /* class => means that T should be a reference type */ , new() /* with paramterless constructor*/
  41.     {
  42.         private readonly List<T> list = new List<T>();
  43.         public void remove(T item)
  44.         {
  45.             list.Remove(item);
  46.         }
  47.         public void add(T item)
  48.         {
  49.             list.Add(item);
  50.         }
  51.  
  52.         public IEnumerator<T> GetEnumerator()
  53.         {
  54.             foreach (T item in list)
  55.             {
  56.                 yield return item; // Yield each item in the collection
  57.             }
  58.         }
  59.  
  60.         IEnumerator IEnumerable.GetEnumerator()
  61.         {
  62.             return GetEnumerator();
  63.         }
  64.  
  65.         public int counter => list.Count;
  66.  
  67.     }
  68.  
  69. }
  70.  
  71.  
  72.  
  73.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement