http://www.dotnetperls.com/icomparable
using System;
using System.Collections.Generic;
class Employee : IComparable
{
private int salary;
private string name;
public Employee(string name, int salary)//public constructor
{
this.salary = salary;
this.name = name;
}
public string getName()
{
return name;
}
public int getSalary()
{
return salary;
}
public int CompareTo(Employee other)
{
// Alphabetic sort if salary is equal. [A to Z]
if (this.salary == other.salary)
{
return this.name.CompareTo(other.name);
}
// Default to salary sort. [High to low]
return other.salary.CompareTo(this.salary);
}
public override string ToString()
{
// String representation.
return this.salary.ToString() + "," + this.name;
}
}
class Program
{
static void Main()
{
List
list.Add(new Employee() { Name = "Steve", Salary = 10000 });
list.Add(new Employee() { Name = "Janet", Salary = 10000 });
list.Add(new Employee() { Name = "Andrew", Salary = 10000 });
list.Add(new Employee() { Name = "Bill", Salary = 500000 });
list.Add(new Employee() { Name = "Lucy", Salary = 8000 });
// Uses IComparable.CompareTo()
list.Sort();
// Uses Employee.ToString
foreach (var element in list)
{
Console.WriteLine(element);
}
Console.ReadKey();
}
}
/*
500000,Bill
10000,Andrew
10000,Janet
10000,Steve
8000,Lucy
*/
Posted Oct 29, 2013, 7:32 AM
VulpesPosted Oct 29, 2013, 6:46 AM
The 'salary' field is now protected from invalid input. The upper limit may be silly but it makes the point!
Posted Oct 29, 2013, 5:29 AM
VulpesPosted Oct 29, 2013, 4:18 AM
Data protection is still possible with object initializers but you have to do it through 'ordinary' properties - you can't use methods for this purpose.
In the DNP article, they were using public properties though there was no possibility of data protection because the properties were 'automatic' i.e. the backing fields and code for the properties were automatically generated by the compiler.
Ken HPosted Oct 29, 2013, 12:03 AM
// output result should is:
Posted Oct 28, 2013, 10:58 PM
VulpesPosted Oct 28, 2013, 7:05 PM
As a result of the modifications you've made it no longer has public properties with these names. I'd therefore use its constructor instead. For example:
list.Add(new Employee("Bill", 10000));