TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Maha
NA
0
325.9k
IComparable.CompareTo
Aug 17 2012 2:10 PM
In this program how to determine which should be plus sign and which should be minus sign (
this
.ID and tem.ID). If you have changed the sing, output is same as input. Code is highlighted in the program. For example:-
return
(
-
this
.ID
+
tem.ID); // Note:
this
.ID has minus sign and tem.ID has plus sign
input
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
output
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
using System;
namespace ConsoleApplication1
{
class StudetCompare
{
static void Main(string[] args)
{
int x;
Student[] student = new Student[3];
for (x = 0; x < student.Length; ++x)
{
student[x] = new Student();
Console.Write("Student #{0} ID = ", x + 1);
student[x].ID = Convert.ToInt32(Console.ReadLine());
}
Console.WriteLine();
Array.Sort(student);
for (x = 0; x < student.Length; ++x)
{
Console.WriteLine("Student #{0} ID = {1}", x + 1, student[x].ID);
}
Console.ReadKey();
}
}
class Student : IComparable
{
public int ID;
public int CompareTo(object student)
{
Student tem = (Student)student; //IComparable is non generic therefore casting
return
(
this
.ID - tem.ID);
}
}
}
/*
Student #1 ID = 300
Student #2 ID = 200
Student #3 ID = 100
Student #1 ID = 100
Student #2 ID = 200
Student #3 ID = 300
*/
Reply
Answers (
2
)
Highlight words in multiple files
How to check the row count of the last page of a grid where paging is true