The "is" operator enables you to check whether one type or class is compatible with another type or class; it returns a Boolean value.
This what website says (http://www.developer.com/net/csharp/article.php/1482651/Working-with-Interfaces-in-C.htm).
If to check one type or class is compatible with another type or class what is the point of casting again in this program. Problem is highlighted.
using System;
using System.Collections;
public class Person : IComparable
{
private string firstname;
private string lastname;
private int age;
public string Firstname
{
get { return firstname; }
set { firstname = value; }
}
public string Lastname
{
get { return lastname; }
set { lastname = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public Person(string firstname, string lastname, int age)
{
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
}
public override string ToString()
{
return String.Format("{0} {1}, Age = {2}", firstname, lastname, age);
}
public int CompareTo(object obj)
{
if (obj is Person)//Checking whether obj is compatible with type Person
{
Person p2 = (Person)obj; //What is the point of casting again
return firstname.CompareTo(p2.Firstname);
}
else
throw new ArgumentException("Object is not a Person.");
}
}
public class TestClass
{
public static void Main()
{
ArrayList people = new ArrayList(); //this requires using System.Collections;
people.Add(new Person("John", "Doe", 84));
people.Add(new Person("Abby", "Normal", 25));
people.Add(new Person("Jane", "Doe", 76));
people.Sort();
foreach (Person p in people)
Console.WriteLine(p);
Console.ReadLine();
}
}
/*
Abby Normal, Age = 25
Jane Doe, Age = 76
John Doe, Age = 84
*/