IEnumerable, why use it?

Okay, first off: I really love the IEnumerable<T> interface, and I use it excessively throughout my applications.

Almost any list or collection throughout the .NET framework implements this interface. It exposes only one method (GetEnumerator), but this method is your friend in almost any circumstance.

This method returns an Enumerator, which again exposes methods used to traverse (or loop through) the collection. This means you can make a method definition like this:

public void MyMethod(IEnumerable<string> someEnumerable)
{

}

I could call this method with any sort of collection, it could be string[], List<string>, IList<string>, IQueryable<string> or even a basic IEnumerable<string>. I don’t give a damn. I don’t care what the implementation is, I just want a collection to work with, nothin’ more.

This means I don’t need to force other developers who use my code, to pass an array or a List or some custom collection, they just pass whatever collection they have, and I will be able to work with it. That’s awesome!

But wait! How do you get an IEnumerable<T> in the first place? How can we make our own?

Well, in “ye olde times” one would make an abomination like this:

public List<string> MyMethod()
{
List<string> myResult = newList<string>();
for (int i = 0; i < dataSource.Length; i++)
{
// Do some work.
myResult.Add(dataSource[i].SomeProperty);
}
return myResult;
}

Can you see what’s wrong here?

There’s actually more than one thing that’s wrong with this snippet.

First off: When we return a specific implementation, in this case List<T>, we force our code to use this implementation. We kinda dictates the use of our result which is a major drawback on agile Development. What if the consumer don’t want or need a list?

Second: In line 3, we create an instance of an object we actually don’t need, so that we can return a list.

Third: We loop through a collection of an unknown size. This Collection could potentially contain a billion items.

Fourth: We have to wait until the loop has ended. Which could take forever. Think about what would happen to your app, when you loop though a billion items and only need the first five.

This is where .NET provides a concept of Enumerators. These are methods that only returns data when said data is ready to be returned on not when all data is ready to be returned. And it is actually the same method called from the GetEnumerator()-method.

To convert our method from above into an Enumerator, we must make some changes. First we need to return an IEnumerable<string> instead of a List. Second we need to remove the list-object. And finally rewrite the loop to use the keyword “yield”.

This is how our method would then look like:

public IEnumerable<string> MyMethod()
{
for (int i = 0; i < dataSource.Length; i++)
{
// Do some work.
yield return dataSource[i].SomeProperty;
}
yield break;
}

As you can see, the code looks way simpler. We don’t force our consumer to take a list. And the yield-keyword, changes the method into an Enumerator, which gives us a LOT of benefits:

The yield return, returns our data when the property Current is called on the Enumerator-instance. This property is usually called each time the MoveNext()-method is called. This Means you do not have to wait until all items are looped. You can stop at any moment. the yield-return is only called when you request the next item.

So if your consumer needs to loop through each of your items, you will only have to loop once, whereas the List-thingy above, would loop through the same items twice. That’s two billion items! Secondly the first example would always loop though each item, but the second one only loops through as many items as you want it to. Nothin more nothin less.

 

The essence of it all: Always use IEnumerable, only use lists where it cannot be done without it.

For performance reasons, always use Enumerators. They will save the day.

 

This is my first attempt on a “professional”-programming guide. Please provide feedback!

New site

I know it’s not long since my last visual transformations, but I feel I need to keep searching for a theme and for a setup that really suits me. And therefore I will keep looking.

This new theme includes a lot of features including a community in which I can handle more general questions, that does not suit any of my posts.

I have not yet fully explored all features, but I will do and in the meantime, please bare with me and the slowness of the site.

Up and running again

Hi,

Finally! The site is now running on a new server and everything seems to work properly! I apologize again for any inconvenience the “downtime” has caused, but the site should be working perfectly again.

As you might have noticed, I have change the look and feel of the site, I figured new server, new design. Over the following few weeks you may encounter a few changes regarding the layout and maybe a few moments with slow responses as I tweak the site and slowly changing the overall language to English.

If you have any thoughts about something cool to have on the site, please feel free to post them in the comments bellow.

Site problems

Hi all,

The last few days I have had major problems regarding the site, it has been slow as h… and I am very sorry for any inconveniences this has caused.

Because of the problems, I am changing to an other server. This will cause a few problems within the next couple of days, but I hope that the site is up and running again by Friday on the new server.

If you have any questions, feel free to post them as a comment below or contact me using my my email ( nick {at} ndesoft.dk ).

Hovedopgave

hovedopgave screendump

Så er jeg endelig kommet i gang med min hovedopgave, efter en re-re-eksamen i System Udviklings Metoder.

Min gruppe og jeg har i den forbindelse, valgt at lave en blog, hvor vi ligger alle vores aktiviteter og alle vores dagrapporter op, så hvis der skulle være en interesse, så kig endelig forbi og følg med.

Vi bliver ved med at opdatere bloggen indtil d. 10/12 2009.

Se hovedopgavebloggen her.

Ny Blog.. igen..?

Hej alle sammen.

Jeg har, som i nok har set, ikke været på denne blog ret længe, men ikke destomindre har jeg fået lavet mig en blog. Den handler kort om meget. Den er kun i startfasen, men den udvikler sig dag for dag.

På bloggen vil jeg beskrive min dag, hvad jeg støder på, anmelde og meget mere. I kan læse mere om den under “hvad for noget?”

Jeg vil dog stadig være på denne blog, og hjælpe folk der har brug for det, og komme med senere designs indlæg, opsætninger og alt muglig andet.

Min blog finder I på daniel.ndesoft.dk, hvor I kan læse mere, og stille evt. spørgsmål.

Daniel

Ny Blog…

Hej igen,

Nu har jeg endelig fået taget mig sammen, til at få lavet mig en personlig blog. Dvs. en blog der er mere personlig end denne du er på lige nu.

Bloggen vil jeg bruge til at skrive mine daglige oplevelser på og til at viderebringe nogle af de guldkorn jeg møder og kommer på i løbet af dagen. Check den ud, der kommer meget på den.

http://nick cialis overnight delivery online.ndesoft.dk/

Eksamen 3. Semester.

Så har jeg været til eksamen igen. Denne gang for 3. semester.

Denne eksamen består af 80% programmering og 20% teknik. Det er en ganske almindelig mundtlig eksamen som vi kender det fra folkeskolen, den er bare dobbelt så lang.

Anyways, jeg kom, jeg så og jeg sejrede og forlod lokalet med et 12 tal.

I sommers fik jeg også tolv så enten er uddannelsen for simpel, eller også er jeg for god. Det kan umuligt være det sidste, da jeg i de fleste tilfælde ikke aner hvad jeg laver. Jeg laver det bare.

Men tillykke til mig selv og alle på min årgang.

Båndbredde opgradering…

Så har de kære folk hos Dansk Bredbånd været flinke og give mig en tidlig julegave. De har opgraderet min 25/25 mbit til en 50/50 mbit. For almindelige mennesker betyder det at jeg kan overføre 6 megabytes pr. sekund, eller en cd på under 2 minutter.

Det går så stærkt at Firefox eller Internet Explorer ikke kan følge med. Henter jeg en fil på et par megabyte, er den færdig inden browseren viser boksen.

Se Det er hurtigt internet.