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
326.2k
IComparable.CompareTo
Feb 26 2012 4:21 PM
This program is altered for simplicity. For example data given to ID 100, 200 and 300. Return will be 1, -1 or 0.
this
.
ID
can take 100, 200 or 300. What value
tem
.
ID
can take. Problem is highlighted.
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 { get; set; }
public int CompareTo(object student)
{
Student tem = (Student)student; //Note: 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 (
7
)
"Object reference not set to an instance of an object." problem
Error (Cant think of subject name)[SOLVED]