Add Methods to Existing Classes

You can add custom features to an existing type as if the type always had the custom features. In this way, you do not have to recompile a given object, nor do you have to create a second, derived object to add these features. Rather, you can add a method to an existing object by using a new compiler feature called extension methods.

Adding methods varies between VB and C#. In VB, you first import the System.Runtime.CompilerServices namespace into your code file. Next, you mark a given Sub or Function with the ExtensionAttribute directive. Lastly, you write a new Sub or Function with the first parameter of the new method being the type you want to extend. The following shows an example. In this example, we extend ...

Get Microsoft® Visual Studio® 2010 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.