Friday 13 September 2013

C# extension methods example

Extension methods can be used extend an existing class without creating a new derived type of the class to be extended or modifying and recompiling the class you want to extend.

Say we have a Utils project in our solution and in that project we have a class with a static method which converts a string to camel case.

To call this method we must add a reference to this project and pass a string to this method:


However, what we can do is change the ToCamelCase method to be an extension method. We do this by modifying the signature of the ToCamelCase method:


To call it now, we call it like we would call any other string method. It even appears in Intellisense!




Note that in an extension method the first parameter is the one to which you apply the 'this' keyword. Any normal parameters that the method should take follow that first parameter.


No comments:

Post a Comment

Scala with Cats: Answers to revision questions

I'm studying the 'Scala with Cats' book. I want the information to stick so I am applying a technique from 'Ultralearning&#...