O'Reilly logo

Microsoft Visual Studio 2015 Unleashed, Third Edition by Mike Snell, Lars Powers

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required