473,396 Members | 1,789 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

about using compare with generics

Hello!

Below I have a complete working program.with some simple classes one of
these is a generic class.

Now If I want to implement functionallity so I can compare animal with each
other or with other animal
for example compare a Chicken with a Cow in some way or a Cow with another
Cow

How is that done?
My attempted strategy is to set a constraint on T in such a way that T is
required to implement the
CompareTo method that exist in IEnumerable<T>
So I change the class definition header for the generic class from this
definition
public class Farm<T: IEnumerable<Twhere T : Animal
to this
public class Farm<T: IEnumerable<Twhere T : Animal, IEnumerable<T>
I then let Cow, Chicken and SuperCow inherit from IEnumarable
and then implement CompareTo in each class which is Cow, Chicken and
SuperCow

I tried this but run into several problems so my strategy was perhaps
complete
wrong.
So how is the correct way of doing this?
using System;
using System.Collections.Generic;
using System.Collections;
using System.Text;

namespace ConsoleApplication15
{
class Program
{
static void Main(string[] args)
{
Farm<Animalfarm = new Farm<Animal>();
farm.Animal.Add(new Cow("Jack"));
farm.Animal.Add(new Chicken("Vera"));
farm.Animal.Add(new Chicken("Sally"));
farm.Animal.Add(new SuperCow("Kevin"));

farm.MakeNoises();

Farm<CowdairyFarm = farm.GetCows();
dairyFarm.FeedTheAnimals();

foreach (Cow cow in dairyFarm)
if (cow is SuperCow)
((SuperCow)cow).Fly();

Farm<AnimalnewFarm = farm + dairyFarm;
Console.ReadKey();
}
}

public abstract class Animal
{
string name;
public Animal(string name)
{ this.name = name; }

public string Name
{ get { return name; } }

public abstract void MakeANoise();
public abstract void Feed();
}

public class Chicken : Animal
{
public Chicken(string name) : base(name) {}

public override void MakeANoise()
{ Console.WriteLine("{0} says 'cluck!'", Name); }

public override void Feed()
{ Console.WriteLine("{0} has been feed(Chicken)", Name); }
}

public class Cow : Animal
{
public Cow(string name) : base(name) {}

public override void MakeANoise()
{ Console.WriteLine("{0} says 'moo!'", Name); }

public override void Feed()
{ Console.WriteLine("{0} has been feed(Cow)", Name); }
}

public class SuperCow : Cow
{
public SuperCow(string name) : base(name) {}

public void Fly()
{ Console.WriteLine("{0} is flying!", Name); }

public override void MakeANoise()
{ Console.WriteLine("{0} says 'here I come to save the day!'",
Name); }

public override void Feed()
{ Console.WriteLine("{0} has been feed(SuperCow)", Name); }
}

public class Farm<T: IEnumerable<Twhere T : Animal
{
private List<Tanimals = new List<T>();

public List<TAnimal
{ get { return animals; } }

public IEnumerator<TGetEnumerator()
{ return animals.GetEnumerator(); }

IEnumerator IEnumerable.GetEnumerator()
{ return animals.GetEnumerator(); }
public void MakeNoises()
{
foreach (T animal in animals)
animal.MakeANoise();
}

public void FeedTheAnimals()
{
foreach (T animal in animals)
animal.Feed();
}

public Farm<CowGetCows()
{
Farm<CowcowFarm = new Farm<Cow>();
foreach (T animal in animals)
if (animal is Cow)
cowFarm.animals.Add(animal as Cow);
return cowFarm;
}

public static Farm<Toperator +(Farm<Tfarm1, Farm<Tfarm2)
{
Farm<Tresult = new Farm<T>();
foreach (T animal in farm1)
result.Animal.Add(animal);

foreach (T animal in farm2)
if (!result.Animal.Contains(animal))
result.Animal.Add(animal);
return result;
}

public static implicit operator Farm<Animal>(Farm<Tfarm)
{
Farm<Animalresult = new Farm<Animal>();

foreach(T animal in farm)
result.Animal.Add(animal);
return result;
}
}
}

//Tony
Jun 27 '08 #1
6 1553
On Jun 19, 1:13*pm, "Tony" <johansson.anders...@telia.comwrote:
Here I have put a constraint on the generic class farm as to
force T to implement the IComparable interface.

I just wonder can this be done in a better way because I don't have strong
types in CompareTo method which is impemented in all classes except the abstract
class ?
Well, for a start you should think about implementing IComparable<T>
instead of IComparable.

But also you really need to think about Marc's questions. How do you
want a Cow to compare to a Chicken? To another Cow? To an animal type
it's never seen before?

Jon
Jun 27 '08 #2
Tony wrote:
Hello!

Below I have a complete working program.with some simple classes one of
these is a generic class.

Now If I want to implement functionallity so I can compare animal with each
other or with other animal
for example compare a Chicken with a Cow in some way or a Cow with another
Cow

How is that done?
First you have to specify what you want the comparison to do.

You can already compare the objects:

if (cow1 == cow2) { ... }

However, this comparison uses the default reference comparison, so that
is probably not what you want to do. So, you have to determine what it
is that you want to do.
My attempted strategy is to set a constraint on T in such a way that T is
required to implement the
CompareTo method that exist in IEnumerable<T>
So I change the class definition header for the generic class from this
definition
public class Farm<T: IEnumerable<Twhere T : Animal
to this
public class Farm<T: IEnumerable<Twhere T : Animal, IEnumerable<T>
I then let Cow, Chicken and SuperCow inherit from IEnumarable
and then implement CompareTo in each class which is Cow, Chicken and
SuperCow

I tried this but run into several problems so my strategy was perhaps
complete
wrong.
Making an animal enumerable doesn't seem to make much sense.

Looping through a cow sound wrong in so many ways... ;)

Besides, the IEnumerable<Tinterface doesn't contain any CompareTo
method. Do you mean the IComparable<Tinterface?
--
Göran Andersson
_____
http://www.guffa.com
Jun 27 '08 #3
Hello!

If I want to implement the generic interface IComparable<Tinstead of the
non-generic how is that done.
I can change the constraint on T to IComparable<Tinstead of IComparable
in the class header definition for Farm.

But how do I write the class definition header for Cow for example now I
have
public class Cow : Animal, IComparable

I can't use any T here!

//Tony


"Jon Skeet [C# MVP]" <sk***@pobox.comskrev i meddelandet
news:28**********************************@e39g2000 hsf.googlegroups.com...
On Jun 19, 1:13 pm, "Tony" <johansson.anders...@telia.comwrote:
Here I have put a constraint on the generic class farm as to
force T to implement the IComparable interface.

I just wonder can this be done in a better way because I don't have strong
types in CompareTo method which is impemented in all classes except the
abstract
class ?
Well, for a start you should think about implementing IComparable<T>
instead of IComparable.

But also you really need to think about Marc's questions. How do you
want a Cow to compare to a Chicken? To another Cow? To an animal type
it's never seen before?

Jon
Jun 27 '08 #4
On Jun 19, 3:03*pm, "Tony" <johansson.anders...@telia.comwrote:
But how do I write the class definition header for Cow for example now I
have
public class Cow : Animal, IComparable

I can't use any T here!
You don't need to:

public class Cow : Animal, IComparable<Cow>

Jon
Jun 27 '08 #5
Looping through a cow sound wrong in so many ways... ;)

OK, that made me chuckle. However, I'm more concerned about SuperCow -
sounds like the marketing strategy for GE livestock...

Marc
Jun 27 '08 #6
The odd thing is; in a funny way there is a sensible OO answer here...
now, I don't like the idea of a Cow having to know how to compare itself
to a Duck a Cat and a Chicken, so IComparable[<T>] might not be easy.

However, lets assume we have a base-class Animal (Cow : Animal, etc); if
you just have a list of animals (List<Animal>), and an external
comparer, say:

Farmer : IComparer<Animal>

then you can get your Farmer instance (or whatever) to do the sort:

List<Animalanimals = ...
animals.Sort(farmer);

or ditto with Array.Sort<Animal>(animalArray, farmer);

Of course, the farmer still needs to have a sensible set of rules for
comparing each animal.

If you are comparing based on a property common to all Animal instances
- their Name, say (do farmers name their animals?), then it is much easier:

animals.Sort((x,y) =string.Compare(x.Name, y.Name));

Marc
Jun 27 '08 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: Matthew W. Jackson | last post by:
I had a question about the "using" statement and Generics in the next version of C#, and I was directed to this newsgroup. My question is: Will the following syntax be valid? using...
2
by: Wiktor Zychla | last post by:
I've read several documents about upcoming C# generics and I still cannot understand one thing. Would it be valid to write a code like this: class SomeClass { public void AMethod<T>(T a, T...
12
by: Michael S | last post by:
Why do people spend so much time writing complex generic types? for fun? to learn? for use? I think of generics like I do about operator overloading. Great to have as a language-feature, as...
5
by: Disccooker | last post by:
and i'm lost. any ideas? It's an object with a public property that is an Int. i receive an Array of these objects and copy them to an arraylist. i need to sort it based on this property and i...
11
by: herpers | last post by:
Hello, I probably don't see the obvious, but maybe you can help me out of this mess. The following is my problem: I created two classes NormDistribution and DiscDistribution. Both classes...
11
by: hammad.awan_nospam | last post by:
Hello, I'm wondering if it's possible to do the following with Generics: Let's say I have a generic member variable as part of a generic class like this: List<DLinqQuery<TDataContext>>...
3
by: Showjumper | last post by:
Back in asp.net 1.1 i made custom collection classes per Karl Seguin's article On the Way to Mastering ASP.NET: Introducing Custom Entity Classes to take advantage of strongly typed data. Now with...
1
by: Doug | last post by:
Hi, I have a collection of objects and I need to compare each item in the collection to see if it's a match on any or all of the others. I have stored my collection in an item like so: ...
8
by: Tony Johansson | last post by:
Hello! I have read that in practice, casting proved to be several times faster than using a generic. So the main reason to use generics is not that the performance is better because that's...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.