Home


.Net, SQL and softball. Musings of a software developer with a softball problem

Friday, June 12, 2009

Extension Methods

So while running around playing with Linq, I just happened across another article by ScottGu, that talks about extension methods. And I have decided that they are truly awesome.

Extension methods allow you to add methods to existing types. In ScottGu's article he adds a called IsValidEmailAddress method to the string type. I originally had great plans on using this in a project to add some extension methods to a base type so they would show up on all the children. And then I realized that I could do the same thing by just writing the function in the base class instead. Same result. So the real use for these things are when you cannot modify the type definition.

So below is the extension method that I originally was going to use. It has all the syntax you need and it worked. I just realized that it was overkill, however awesome it may be. Lookup and LookupElement are parent classes for all of the lookup objects in the project. Lookup is a list of lookupElements.
public static string GetTextFromValue(this Lookups.Lookup L, int ID){
string text = "";
foreach (Lookups.LookupElement le in L) {
if (le.Value == ID){
text = le.Text;
break;
}
}
return text;
}
So after building this a new method would show up in IntelleSense when you used a Lookup object. And you would use it just like you would a normal method call.

Labels:

posted by Tom Becker at

1 Comments:

Blogger yoerayo said...

Cool, but Ruby does this much nicer :)

June 19, 2009 11:03 PM

 

Post a Comment

<< Home