Recent Posts
Archives
Topics

Wednesday, January 28, 2009

 

A lesson in Extension Methods

With C# 3.0, you were given the ability to extend any object. That's right... if some object objFred has a method that takes two parameters -- string and int -- and you need it to take string and double, you can now "roll your own".

I needed to do this very thing this week. In my class, I needed to make a call to a system class. But I needed it to return one of the objects I'd created instead of a double or string.

Yes, I could have just created a method in my own class to handle this, but I wanted to logically keep the method as part of the main library.


public EngVar ConvertToEng(this string str)
{
if (String.IsNullOrEmpty(str)) return null;

EngVar V = new EngVar();
try {
V.Parse(str);
}
catch
{
return null;
}
}


Now, within my code (as long as this is in scope), intellisense has a new method called ConvertToEng() for every string in my project. Could I have just used the Parse(string x) method within my code? Yes. But having it handy within intellisense makes coding much faster. And I've found that, for my mind, having it hang off of 'string' makes much more sense.


...

string MyString = "E15ft/s^2";

...

EngVar V = MyString.ConvertToEng();



This just seems to me to be much cleaner and more logical to read.

Labels:


Comments:

Post a Comment



Links to this post:

Create a Link



<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]