C# Yield Statement Demystified With Examples

The yield statement has been released with .NET 2.0 framework, but many still do not know what it does. In a nutshell, it does transformations – obtaining a result dataset given an input dataset. Since the time yield has seen its debut, there are different and simpler ways of doing the same thing. However, the yield keyword can give you a break if you are purely transforming one Type into another, when it could make sense to create a separate method versus a LINQ expression.

As an example, you may have a number of Car objects that you have for sale and a customer asks for cars that have at most 50k miles and are green.

An old style C# code looks like this:

public List GetCars(int miles, string color)
{
	var cars = new List();
	foreach (var car in CarsForSale)
	{
		if (car.Price > 50000 || car.Color != "green") { return; }
		cars.Add(car);
	}
	return cars;
}

A yield C# code looks like this:

public List GetCars(int miles, string color)
{
	foreach (var car in CarsForSale)
	{
		if (car.Price > 50000 || car.Color != "green") { return; }
		yield car;
	}
}

A LINQ C# code looks like this:

public List GetCars(int miles, string color)
{
	return CarsForSale.Where(car => car.Price <= 50000 && car.Color == "green").ToList();
}

So, while yield can be interesting, all of the functionality it provides can be achieved with LINQ. If you haven't looked at LINQ yet – now is the time, for you are late.

This entry was posted in .NET and tagged , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *