Wednesday, June 8, 2011

C# Extension Methods Really Do Exist - Are there Extension Properties?

I learned about this sometime ago in Javascript and I thought it was a brilliant feature.  Well today I just learned it was also available in C#3 and above.  Sometimes my blindness amazes me and I cant believe I did not see this sooner given I used in it javascript about 6-7 years ago.

Well here is the MSDN link for extensions.
http://msdn.microsoft.com/en-us/library/bb383977.aspx

Example:
namespace ExtensionMethods
{
    public static class MyExtensions
    {
       public static int WordCount(this String str)
        {
            return str.Split(new char[] { ' ', '.', '?' },
                             StringSplitOptions.RemoveEmptyEntries).Length;
        }
    }  
}


string s = "Hello Extension Methods";
int i = s.WordCount();


This syntax really allows you to write cleaner code.  Extending the built in .net objects is just as easy as adding new methods to your own classes.  I have seen people mentioning extending properties on forumns but Im not really sure if that is possible or they were just complaining about it.  I will need to research that a little further.  1 person mentioned he would like to do something like the following with extension properties which I think would also be nice to have.
DateTime d = 20.Minutes.Ago

No comments:

Post a Comment