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
327.7k
Generic
Aug 5 2013 5:00 PM
In the following program if you included a step Console.WriteLine(".." + o.GetType() + ".."); next to public int CompareTo(
object
o) the output saying that "o" is
Element
data type. Problem is highlighted.
So why it is necessary to change
object
data type into
Element
data type
(
public int
CompareTo(
Element
o))
if it is a generic class
(
class
Element
:
IComparable
<
Element
>)
.
using System;
public class ClassArr
{
static public void Main()
{
Element[] Arr = new Element[] { new Element(8), new Element(3), new Element(12), new Element(7) };
Array.Sort(Arr);
Console.WriteLine("Sorted:");
for (int x = 0; x < Arr.Length; ++x)
Console.WriteLine("The instance number is {0}", Arr[x].getInstance());
Console.ReadKey();
}
}
class Element : IComparable
{
int instance;
public Element(int instance)
{
this.instance = instance;
}
public int getInstance()
{
return this.instance;
}
public int CompareTo(object o)
{
Console.WriteLine(".." + o.GetType() + "..");
if (o.GetType() != this.GetType())
throw (new ArgumentException());
Element elem = (Element)o;
return (this.instance - elem.instance);
}
}
/*
Sorted:
The instance number is 3
The instance number is 7
The instance number is 8
The instance number is 12
*/
Reply
Answers (
4
)
Error in Asp.net
Regex to Validate a filename