Create a Generic Type - CSharp Custom Type

CSharp examples for Custom Type:Generics

Description

Create a Generic Type

Demo Code

using System;// w w w.ja  v a2 s. c  om
using System.Collections.Generic;
public class Bag<T>
{
   private List<T> items = new List<T>();
   public void Add(T item)
   {
      items.Add(item);
   }
   public T Remove()
   {
      T item = default(T);
      if (items.Count != 0)
      {
         Random r = new Random();
         int num = r.Next(0, items.Count);
         // Remove the item
         item = items[num];
         items.RemoveAt(num);
      }
      return item;
   }
   public IEnumerator<T> GetEnumerator()
   {
      return items.GetEnumerator();
   }
   public T[] RemoveAll()
   {
      T[] i = items.ToArray();
      items.Clear();
      return i;
   }
}
class MainClass
{
   public static void Main(string[] args)
   {
      Bag<string> bag = new Bag<string>();
      bag.Add("D");
      bag.Add("B");
      bag.Add("G");
      bag.Add("M");
      bag.Add("N");
      bag.Add("I");
      foreach (string elem in bag){
         Console.WriteLine("Element: {0}", elem);
      }
      Console.WriteLine("\nRemoving individual elements");
      Console.WriteLine("Removing = {0}", bag.Remove());
      Console.WriteLine("Removing = {0}", bag.Remove());
      Console.WriteLine("Removing = {0}", bag.Remove());
      Console.WriteLine("Removing = {0}", bag.Remove());
      foreach (string elem in bag){
         Console.WriteLine("Element: {0}", elem);
      }
      string[] s = bag.RemoveAll();
      foreach (string elem in bag){
         Console.WriteLine("Element: {0}", elem);
      }
   }
}

Result


Related Tutorials