Categories
Geeky/Programming

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;
            }
            else
            {
                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:

if(myDataset.IsEmpty())
{

}

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

By Steve Novoselac

Director of Digital Technology @TrekBikes, Father, Musician, Cyclist, Homebrewer

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

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. πŸ˜›

Like

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.