RSS

Extract yield lines to common method

07 Apr

Recently I wanted to refactor out some common lines out of our auto generated code and our hand written code.

The common lines of code were:

if (obj.IsNull()) yield break;
foreach (var m in obj)
{
	m.AcceptChanges();
	yield return m;
}

An example of a method to be refactored is

public IEnumerable<MyModels.StatusLookup> GetAll()
{
	var results = Database.Current.pStatusLookupLoadAll()
		.ExecuteTypedList<MyModels.StatusLookup>();
	if (results.IsNull())
		yield break;
	
	foreach (var m in results)
	{
		//..Common logic lines...  //..Common logic lines...
		yield return m;
	}
}

My attempts at creating an IEnumerable extension method were failing so I asked my question on stackoverflow. And viola my question was answered.

http://stackoverflow.com/questions/5557019/extract-yield-lines-into-common-method/5561020#comment-6342765

Here is the proper extension method

// Note: We are using a generic type constraint on T.
public static IEnumerable<T> AcceptChangesAndYield<T>
	(this IEnumerable<T> obj)
	where T : MyModels.Interfaces.ILookup
{
	if (obj.IsNull())
		yield break;
	foreach (var m in obj)
	{
		//Put custom code here above the yield
		yield return m;
	}
}
Advertisements
 
Leave a comment

Posted by on April 7, 2011 in .Net, C#, Extension

 

Tags: , ,

Leave a Reply

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

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 )

Google+ photo

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

Connecting to %s

 
%d bloggers like this: