13
Answers

IComparable

Ask a question
Maha

Maha

12y
1.5k
1
This orignal program is in the following website (http://www.dotnetperls.com/icomparable).List of name and salary have been added in following way list.Add(new Employee() { Name = "Steve", Salary = 10000 });

If we remove the curly braces, Name, and Salary and we write like as follows list.Add(new Employee("Steve", 10000)); Program is requesting a public constructor. And we add a public constructor. The output is as follows. Please explain the reason. Modification is highlighted in the program.

/*
8000,Lucy
500000,Bill
10000,Andrew
10000,Janet
10000,Steve
*/

using System;
using System.Collections.Generic;

class Employee : IComparable<Employee>
{
public int Salary { get; set; }
public string Name { get; set; }

public Employee(string Name, int Salary)
{
this.Name = Name;
this.Salary = 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.Name.CompareTo(this.Name);
}

public override string ToString()
{
// String representation.
return this.Salary.ToString() + "," + this.Name;
}
}

class Program
{
static void Main()
{
List<Employee> list = new List<Employee>();
list.Add(new Employee("Steve", 10000));
list.Add(new Employee("Janet", 10000));
list.Add(new Employee("Andrew", 10000));
list.Add(new Employee("Bill", 500000));
list.Add(new Employee("Lucy", 8000));

// Uses IComparable.CompareTo()
list.Sort();

// Uses Employee.ToString
foreach (var element in list)
{
Console.WriteLine(element);
}
Console.ReadKey();
}
}


Answers (13)