h1

VB Extension Methods > C# Extension Methods =(

July 31, 2008

As my title childishly explains VB extension methods seem to have one over c# extension methods. Yesterday I found the following limitation in c#: You cannot modify the object you are calling the extension method on by ref. you must create a copy of the object and pass it as a return value. An example will make this clearer. You CAN do this:

public static IEnumerable<T> AddRange<T>(this IEnumerable<T> list, IEnumerable range)
{
List<T> totalList = new List<T>();

foreach (T t in list)
{
totalList.Add(t);
}

foreach (T t in range)
{
totalList.Add(t);
}

return totalList;
}

You can NOT do this

public static void AddRange<T>(this IEnumerable<T> list, IEnumerable range)
{
List<T> totalList = new List<T>();

foreach (T t in list)
{
totalList.Add(t);
}

foreach (T t in range)
{
totalList.Add(t);
}

list = totalList;
}

It’s a sad day today my c# friends ;p

Advertisements

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: