title: Compare 2 Objects of Generic Class Type in C#
body: <p>I have a homework and I have to compare 2 object's by one of their properties, but since I'm working with generic types on my linked list where I have to store the objects I can't really reach the object's certain property (I'm using an interface, and all of the classes implement that interface)
  So I have got a major interface, and some classes (i.e. class1, class2) that inherit the interface properties such as Age, or any kind of number that is comparable easily. In Main() I just created a new LinkedList and created some class1, class2 objects. I put them in the ordered list with that SortedListAddElement method, but I'm stuck at the part where it should compare the element's by the int properties. How should I go on from there with this source code? Should I change the first line to: class List : IEnumerable, IComparable, IMajorInterface? Or change something in CompareTo()? Please help!</p>
  
  <pre><code>interface IMajorInterface 
  { 
      string Name{ get; } 
      int Age { get; set; } 
  }
  
  class List&lt;T&gt; : IEnumerable&lt;T&gt;, IComparable&lt;T&gt;
  {
      ListElement&lt;T&gt; head;
  
      public List()
      {
          head = null;
      }
  
      public void SortedListAddElement(T newValue)
      {
          ListElement&lt;T&gt; new = new ListElement&lt;T&gt;(newValue);
          ListElement&lt;T&gt; p = head;
          ListElement&lt;T&gt; e = null;
          while (p != null /* &amp;&amp; this is the part where I should compare the p and new objects by their property, for example the Age property, like: p.Age &lt; new.Age */)
          {
              e = p;
              p = p.Next;
          }
          if (e == null)
          {
              new.Next = head;
              head = new;
          }
          else
          {
              new.Next = p;
              e.Next = new;
          }
      }
  
      public int CompareTo(T obj)
      {
          if (obj == null)
          {
              return -1;
          }
          else
          {
              if (obj is T)
              {
                  T obj2 = obj as T;
                  return obj.Age.CompareTo(obj2.Age);
              }
              else
              {
                  return -1;
              }
          }
      }
  </code></pre>