c# - How to Implement IComparable interface? -
i populating array instances of class:
bankaccount[] a; . . . = new bankaccount[] { new bankaccount("george smith", 500m), new bankaccount("sid zimmerman", 300m) }; once populate array, sort balance amounts. in order that, able check whether each element sortable using icomparable.
need using interfaces. far have following code:
public interface icomparable { decimal compareto(bankaccount obj); } but i'm not sure if right solution. advice?
you should not define icomparable yourself. defined.
rather, need implement icomparable on bankaccount class.
where defined class bankaccount, make sure implements icomparable interface
then write bankaccout.compareto compare balance amounts of 2 objects.
edit
public class bankaccount : icomparable<bankaccount> { [...] public int compareto(bankaccount that) { if (this.balance > that.balance) return -1; if (this.balance == that.balance) return 0; return 1; } } edit 2 show jeffrey l whitledge's answer:
public class bankaccount : icomparable<bankaccount> { [...] public int compareto(bankaccount that) { return this.balance.compareto(that.balance); } }
Comments
Post a Comment