IComparable<> inheritance in SortedDictionary

[Test]
public void Test()
{
  var dic = new SortedDictionary<BaseClass, string>();
  dic.Add(new BaseClass(){Number = 1}, "");
  dic.Add(new ExtendClass(){Text = "One"}, "");
 
  Assert.True(dic.ContainsKey(new BaseClass() { Number = 1 }));
  Assert.False(dic.ContainsKey(new BaseClass() { Number = 2 }));
  Assert.True(dic.ContainsKey(new ExtendClass() { Text = "One" }));
  Assert.False(dic.ContainsKey(new ExtendClass() { Text = "Two" }));
}
 
public class BaseClass : IComparable<BaseClass>
{
  public int Number { get; set; }
 
  public virtual int CompareTo(BaseClass other)
  {        
    return Number.CompareTo(other.Number);
  }
}
 
public class ExtendClass : BaseClass, IComparable<ExtendClass>
{
  public string Text { get; set; }
 
  public override int CompareTo(BaseClass other)
  {
    var other2 = other as ExtendClass;
    return other2 == null ? base.CompareTo(other) : CompareTo(other2);
  }
 
  public int CompareTo(ExtendClass other)
  {        
    return Text.CompareTo(other.Text);
  }
}

Comments

Popular posts from this blog

Tibco Rendezvous (tibrv) C# .Net example

Parse XML to dynamic object in C#