Click here to Skip to main content
15,885,278 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help me describe this code.
C#
public int CompareTo(object obj)
{
if (obj is Person)
{
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
}
else
{
throw new ArgumentException(
"Object to compare to is not a Person object.");
}
}

in particular i intresting.What this two lines created for?
C#
Person otherPerson = obj as Person;
return this.Age - otherPerson.Age;
Posted

C#
// input obj cast to Person 
Person otherPerson = obj as Person;
// return the difference of Age values of both comparing objects 
return this.Age - otherPerson.Age;

Read the documentation of IComparable Interface[^] CompareTo method should return integer value based on the comparison, here two objects are consider as in same position if the age values are equal.
 
Share this answer
 
v2
The as operator checks the given object and if it can be converted to the given type returns it as that type. Otherwise, it returns null. It's used when you don't know what type of value is being passed into a method (often an event handler) and you need to check so that you don't cause problems by trying to use it as a type it isn't:
For example:
C#
ListBox lb = new ListBox();
...
Control c = lb;
...
TextBox tb = c as TextBox;
will give tb/code> as <code>null becasue a ListBox cannot be converted into a Textbox, whereas
C#
TextBox tb = new TextBox();
...
Control c = tb;
...
TextBox tb2 = c as TextBox;
will give tb2 as a TextBox instance.

It's a safe way of checking the type without potentially causing a type casting exception if the conversion cannot be made.

The second line subtracts two property (or field) values and returns the result to the calling method.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900