Hussein Zawawi
Hussein Zawawi

Reputation: 2927

IEnumerable evaluation

In this implementation does hand will be evaluated each time and return another list ?

foreach (Card card in hand.Cards)
{ 

}

Should we replace the above implementation with the following?

var cards = hand.Cards;
foreach (Card card in cards)
{ 

} 

Upvotes: 2

Views: 870

Answers (4)

Maciek Talaska
Maciek Talaska

Reputation: 1638

No. Actually the two snippets result in the same code. In the snippet below:

foreach (Card card in hand.Cards)
{ 

}

hand.Cards is going to be called only once.

Edit:

I've created a small snippet, that I hope will show that there is no difference at all:

void Main()
{
    Hand hand = new Hand();
    foreach( var card in hand.Cards() )
    {
        Console.WriteLine("{0}", card);
    }

    var allCards = hand.Cards();
    foreach( var anotherCard in allCards )
    {
        Console.WriteLine("{0}", anotherCard);
    }
}

public class Card
{
private string _cardName;
public Card( string cardName )
    {
        this._cardName = cardName;
    }

    public override string ToString()
    {
        return this._cardName;
    }
}

public class Hand
{
    public IEnumerable<Card> Cards()
    {
        yield return new Card("Ace");
        yield return new Card("King");
    }
}

The otuput (for both methods) is as follows:

Ace
King
Ace
King

Upvotes: 4

Saeed Amiri
Saeed Amiri

Reputation: 22555

No there is no difference between this two. Also if they are for EF, they are same query. also in the syntax below:

foreach (Card card in hand.Cards.AsEnumerable())
{ 

}

the hand.Cards.AsEnumerable() will be evaluated at first and will be saved in temporary variable, actually this wont happen in each iteration.

P.S: in general there is no need to call AsEnumerable in foreach loop, I just mentioned this to elaborate foreach evaluation.

Upvotes: 0

Sam Anwar
Sam Anwar

Reputation: 669

The two code snippets you posted above are identical. When you enumerate through a collection that implement the IEnumerable interface, it uses the GetEnumerator method to loop through the items, and it does not create a duplicate copy of the object.

The only difference above is that you're creating a second variable that holds the same reference to the original collection, which doesn't do you any good in this case.

Upvotes: 0

Snake Eyes
Snake Eyes

Reputation: 16764

There are no difference.

But if you use hand.Cards in other code, yes the second should be fine.

Upvotes: 0

Related Questions