Add Methods to Existing Classes (Extension Methods)

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 class, nor do you have to create a second derived class to add these features. Rather, you can add a method to an existing class by using a compiler feature called extension methods.

Adding methods varies between Visual Basic and C#. In Visual Basic, 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. ...

Get Microsoft Visual Studio 2015 Unleashed, Third Edition 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.