Hello!
Below I have a working program.
I have one generic class called Farm<T>
with this header definition public class Farm<T: IEnumerable<Twh ere T :
Animal
Now to my question I changed the inheritance of the IEnumerable from the
generic IEnumerable<T>
to the generel IEnumerable and the program function just the same so no
difference occured.
So what advantage do I get if I implement the generic interface
IEnumerable<Tin stead of the
generell IEnumerable ?
Can you also give me some example that show on advantage to implement the
generic interface IEnumerable<T>?
I know that this IEnumerable<Tin herit from IEnumerable.
So as a summary I can't see what purpose or advantage I get when I
implement IEnumerable<Tin stead of
IEnumerable.?
using System;
using System.Collecti ons.Generic;
using System.Collecti ons;
using System.Text;
namespace ConsoleApplicat ion9
{
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<CowdairyFa rm = farm.GetCows();
dairyFarm.FeedT heAnimals();
foreach (Cow cow in dairyFarm)
{
if (cow is SuperCow)
((SuperCow)cow) .Fly();
}
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.WriteLi ne("{0} says 'cluck!'", Name);
}
public override void Feed()
{
Console.WriteLi ne(Name + " has been feed(Chicken)") ;
}
}
public class Cow : Animal
{
public Cow(string name) : base(name) {}
public override void MakeANoise()
{
Console.WriteLi ne("{0} says 'moo!'", Name);
}
public override void Feed()
{
Console.WriteLi ne(Name + " has been fed(Cow)");
}
}
public class SuperCow : Cow
{
public SuperCow(string name) : base(name)
{ }
public void Fly()
{
Console.WriteLi ne("{0} is flying!", Name);
}
public override void MakeANoise()
{
Console.WriteLi ne("{0} says 'here I come to save the day!'",
Name);
}
public override void Feed()
{
Console.WriteLi ne(Name + " has been feed(SuperCow)" );
}
}
public class Farm<T: IEnumerable<Twh ere T : Animal
{
private List<Tanimals = new List<T>();
public List<TAnimal
{
get { return animals; }
}
IEnumerator IEnumerable.Get Enumerator()
{
return animals.GetEnum erator();
}
public IEnumerator<TGe tEnumerator()
{
return animals.GetEnum erator();
}
public void MakeNoises()
{
foreach (T animal in animals)
animal.MakeANoi se();
}
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;
}
}
}
//Tony 2 2498
Tony Johansson <jo************ *****@telia.com wrote:
Below I have a working program.
I have one generic class called Farm<T>
with this header definition public class Farm<T: IEnumerable<Twh ere T :
Animal
Now to my question I changed the inheritance of the IEnumerable from the
generic IEnumerable<T>
to the generel IEnumerable and the program function just the same so no
difference occured.
In this particular program, yes.
So what advantage do I get if I implement the generic interface
IEnumerable<Tin stead of the
generell IEnumerable ?
You end up with a more strongly typed API. This enables things like
LINQ to Objects to work much more smoothly, and fewer casts which need
to be checked at execution time. (In fact your foreach loops ended up
needing execution time casts anyway, but that's often not the case.)
In general, when you *can* implement a generic interface instead of a
nongeneric one, it's a good idea to do so.
--
Jon Skeet - <sk***@pobox.co m>
Web site: http://www.pobox.com/~skeet
Blog: http://www.msmvps.com/jon.skeet
C# in Depth: http://csharpindepth.com
On Jun 19, 12:05*am, Jon Skeet [C# MVP] <sk...@pobox.co mwrote:
Tony Johansson <johansson.ande rs...@telia.com wrote:
Below I have a working program.
I have one generic class called Farm<T>
with this header definition public class Farm<T: IEnumerable<Twh ereT :
Animal
Now to my question I changed the inheritance of the IEnumerable from the
generic IEnumerable<T>
to the generel IEnumerable and the program function just the same so no
difference occured.
In this particular program, yes.
So what advantage do I get if I implement the generic interface
IEnumerable<Tin stead of the
generell IEnumerable ?
You end up with a more strongly typed API. This enables things like
LINQ to Objects to work much more smoothly, and fewer casts which need
to be checked at execution time. (In fact your foreach loops ended up
needing execution time casts anyway, but that's often not the case.)
In general, when you *can* implement a generic interface instead of a
nongeneric one, it's a good idea to do so.
In addition to all this, there is one more practical reason to
implement IEnumerable<T>: if you do that, then any method that takes
IEnumerable<Twi ll be able to work with your object (and also any
method that takes a plain IEnumerable, since, as you've noticed,
IEnumerable<Tex tends IEnumerable). For example, the vast majority of
LINQ methods require IEnumerable<T>. You can use
Enumerable.Cast <TResult>() method to create wrappers as needed, of
course, but, same as with plain casts, it gets tedious to write it
again and again, and there is an associated performance hit as well. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: Doug Dew |
last post by:
This won't compile:
using IEnumerable<T> = System.Collections.Generic.IEnumerable<T>;
namespace MyNamespace
{
public class MyClass<T> : IEnumerable<T>
{
// Appropriate stuff here
}
|
by: Gustaf |
last post by:
Using VS 2005. I got an 'IpForm' class and an 'IpFormCollection' class,
containing IpForm objects. To iterate through IpFrom objects with
foreach, the class is implemented as such:
public class IpFormCollection : IEnumerable<IpForm>
{
ArrayList forms = new ArrayList();
public IEnumerator<IpFormGetEnumerator()
{
|
by: Andrew Robinson |
last post by:
I have a method that needs to return either a Dictionary<k,vor a List<v>
depending on input parameters and options to the method.
1. Is there any way to convert from a dictionary to a list without
itterating through the entire collection and building up a list?
2. is there a common base class, collection or interface that can contain
either/both of these collection types and then how do you convert or cast
from the base to either a...
|
by: Morgan Cheng |
last post by:
In .Net 2.0, Generics are introduced. I found that IEnumerable<T>
inherites from IEnumerable. This makes implementation of
IEnumerable<Thas to have two GetEnumerator methods defined( one for
IEnumerable<Tand the other for IEnumerable). I doubt why .Net class
hierarchy is designed in such a way. IMHO, they should not have
inheritance releationship, just like IList<Tand IList.
I googled the web and found two related articles....
|
by: Ezmeralda |
last post by:
Hello,
I need to an TCP/IP Interface for communication with an embedded
device.
Since I have two different design ideas in mind, I am wondering
whether
you could give me some hints to decide:
Requirements:
- Interface should be used for company internal purposes/software but
| |
by: Ezmeralda |
last post by:
Hello,
I need to an TCP/IP Interface for communication with an embedded
device.
Since I have two different design ideas in mind, I am wondering
whether
you could give me some hints to decide:
Requirements:
- Interface should be used for company internal purposes/software but
|
by: ajay2552 |
last post by:
Hi,
I have a query.
All html tags start with < and end with >. Suppose i want to display either '<' or '>' or say some text like '<Company>' in html how do i do it?
One method is to use <, > ,<Company> to display '<', '>' and '<Company>' respectively.
But is there any freeware code available which could implement the above functionality without having to use >,< and such stuff???
|
by: Marc Gravell |
last post by:
You could bypass the List<T>'s tendency to use ICollection<Tby
simply not giving it an ICollection<T- for example, with the C# 3
extension method below you could use:
List<Tlist = new List<T>(source.AsEnumerableOnly());
The AsEnumerableOnly() *only* exposes IEnumerable<T(OK, it also
exposes IEnumerable and IDisposable ;-p), allowing your non-Count-
friendly implementation to work happily.
|
by: Berryl Hesh |
last post by:
Converting in the other direction , IEnumerable<Interfaceto
List<ImplInterface>, I can just create a new List<ImplInterface(data)
where data is IEnumerable<Interface>.
How can I convert the List<ImplInterfaceto IEnumerable<Interface>?
Thanks, BH
|
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look !
Part I. Meaning of...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it.
First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
| |
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth.
The Art of Business Website Design
Your website is...
|
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules.
He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms.
Adolph will...
|
by: TSSRALBI |
last post by:
Hello
I'm a network technician in training and I need your help.
I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs.
The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols.
I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
|
by: 6302768590 |
last post by:
Hai team
i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| |
by: bsmnconsultancy |
last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...
| |