Geeks With Blogs
Sean Rhone

Ever got bored of typing the same code over and over again? For example, if you want to use the IDataRecord to process a DataReader you will run into this code a lot:

s.Id = objIDR.GetInt32(objIDR.GetOrdinal("Id"));
s.Name = objIDR.GetString(objIDR.GetOrdinal("Name"));

Over and over again you need to call the GetOrdinal function to get the index of a field in the IDataRecord. You can reduce your typingwork a lot by using Extension Methods. They will encapsulate the GetOrdinal function into a new version of GetString or GetInt32. An Example:

Build a new static class which will contain the Extension Methods.
Add the following code to Extend the GetInt32 method of the IDataRecord interface:

public static Int32 GetInt32(this IDataRecord record, string field)
{
     return record.GetInt32(record.GetOrdinal(field));   
}

Make sure the method is declared static. You pass through 2 parameters. First the IDataRecord. Don't forget the "this" keyword because this is essential for an extension method. The IDataRecord is passed through automatically. Secondly pass through the name of the field you want to get the data from. Internally the GetOrdinal is used to retrieve te value.
But from whithin your app you can now call the GetInt32 method of the IDataReader as follows:

v.Id = objIDR.GetInt32("Id");

Where objIDR is an IDataSource object. You no longer need to code he GetOrdinal method because the exended GetInt32 does this job on its own. You can extend other methods of the IDataSource as well as methods of other data types or classes.

Posted on Thursday, September 24, 2009 8:41 AM | Back to top


Comments on this post: Extension Methods

No comments posted yet.
Your comment:
 (will show your gravatar)
 


Copyright © Ramblings | Powered by: GeeksWithBlogs.net | Join free