C# 3.0 Features – Extension Methods

C# 3.0 and .NET 3.5 are out and ready for consumption, and I have been using some of the new features. One of the new features, Extension Methods, is really cool and can help you consolidate and reuse your code in a logical manner. Take for example, System.Data.DataSet – there is always something I do when getting a DataSet back. Check if it isnull and check if the table in the [0] index has more than zero rows.

Now, you end up having all these if statements to check this every time you get a DataSet back. Something like this:

DataSet myDataset;
myDataset= _database.ExecuteDataSet(dbCommand);

if(myDataset != null && myDataset.Tables[0].Rows.Count > 0)



Now, in previous versions of .NET, you could make a method in a Core library you have, or whatever and pass in the dataset and pass back a bool if that dataset met that condition. What you can do now is this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SteveNovoselac.MyCoreLib.Common.Extensions
    public static class DataExtensions
        public static bool IsEmpty(this DataSet d)
            if (d != null && d.Tables[0].Rows.Count > 0)
                return false;
                return true;

You can see, I created a class called DataExtensions. I have a method "IsEmpty()" that takes "this DataSet d" (this makes it an extension method for DataSet)

Now, in my code I can do this:



Awesome! Next time I will go over Automatic Properties and the pros/cons in them.


One thought on “C# 3.0 Features – Extension Methods”

  1. Proud little geek note for you on this one. :-) REALbasic had extension methods about two years before .NET got them, and it has basically the same syntax and functionality. So when I was at PDC 2005, I met Anders Hejlsberg and had the chance to speak with him briefly. I mentioned I worked on REALbasic and he grinned and said he really liked our “extends” functionality. :-P


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