C# yield

I’ve seen the “yield” keyword here and there… but I’ve never really cared to learn what it does. Until now. Actually, it’s my understanding that it’s more or less a convenience keyword like “var.”

In short, “yield” allows you to return an IEnumerable without creating a List.

Example: (old way)

IEnumerable<Car> FindBlueCars(){
	var blueCars = new List<Car>();
	foreach (var c in _allCars)
		if (c.IsBlue())
			blueCars.Add(c);
	return blueCars;
}

Example: (new way)

IEnumerable<Car> FindBlueCars(){
	foreach (var c in _allCars)
		if (c.IsBlue())
			yield return c;
}

Saves some typing. MSDN reference for yield.

Are you a Git user? Let me help you make project management with Git simple. Checkout Gitpilot.

Read me blog on entrepreneurship: Techneur
Follow me on Twitter: @jprichardson

-JP

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.