Custom Iterators, Anmonymous/Generic Methods and Type Parameters

This article is a short summary/discussion of an excellent MSDN article titled “Custom Iterators” by Bill Wagner available here: http://msdn2.microsoft.com/en-gb/vcsharp/bb264519.aspx

This initially made little or no sense to me. I am unfortunately used to pumping out pretty standard C# code – CRUD SQL plumbing and databinding – not really much mental excersise going on there. However this article is well worth reading as it uses a range of (not very new at all) C# 2.0 features, which will soon become much better known thanks to the advent of LAMBDA expressions and the like.

First of all, Generic Methods and Type Parameters:

A generic type is essentially a placeholder for a real type – and so a generic method is a method that accepts method specefic generic parameters – an example:

public void GenericMethods<T>(T param)
{
Console.WriteLine(param.GetType().ToString());
}

//And to use it:

GenericMethods<string>("sdfsdf");

//Or with type inference:

GenericMethods("sdfsdf");

}

The important thins is that you can reuse this method with different types of data – and where this becomes really interesting is with delegates, because this allows you to setup blueprints (delegates) for methods that perform actions on generic types (and even easier with anonymous methods).

You can then pass these methods into methods that expect this delegate and construct some simple building blocks to reuse in your code.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

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: