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
*/
VulpesRank #55 · 29.2K reputationPosted Oct 28, 2013, 3:05 PM EDT
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));
Posted Oct 28, 2013, 6:58 PM EDT
Ken HRank #2,315 · 610 reputationPosted Oct 28, 2013, 8:03 PM EDT
// output result should is:
VulpesRank #55 · 29.2K reputationPosted Oct 29, 2013, 12:18 AM EDT
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.
Posted Oct 29, 2013, 1:29 AM EDT
VulpesRank #55 · 29.2K reputationPosted Oct 29, 2013, 2:46 AM EDT
The 'salary' field is now protected from invalid input. The upper limit may be silly but it makes the point!
Posted Oct 29, 2013, 3:32 AM EDT
Answer a question in the forums and earn +20 SHARP for every answer.
See unanswered questionsTop experts