Comparing Instances of a Type Parameter : Generic Class « Generics « C# / C Sharp






Comparing Instances of a Type Parameter

Comparing Instances of a Type Parameter
 

using System;

class MyClass : IComparable {
  public int val;

  public MyClass(int x) { 
    val = x; 
  }
  public int CompareTo(object obj) {
    return val - ((MyClass) obj).val;
  }
}

class CompareDemo {
  public static bool contains<T>(T what, T[] obs) where T : IComparable {
    foreach(T v in obs)
      if(v.CompareTo(what) == 0)
        return true;
    return false;
  }

  public static void Main() {
    int[] nums = { 1, 2, 3, 4, 5 };

    if(contains(2, nums))
      Console.WriteLine("2 is found.");

    string[] strs = { "one", "two", "three"};

    if(contains("two", strs))
      Console.WriteLine("two is found.");

    MyClass[] mcs = { new MyClass(1), new MyClass(2),
                      new MyClass(3), new MyClass(4) };

    if(contains(new MyClass(3), mcs))
      Console.WriteLine("MyClass(3) is found.");

  }
}
           
         
  








Related examples in the same category

1.A simple generic classA simple generic class
2.Declare the generic class.
3.A Generic Class with Two Type ParametersA Generic Class with Two Type Parameters
4.Generic Fields
5.Create relationship between two type parameters
6.Demonstrate the default keywordDemonstrate the default keyword
7.'This' Reference for Generic Types
8.Generic class with interfaceGeneric class with interface