Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • DownloadDownload
  • PrintPrint
Share this Page URL
Help

12. OOA&D > Extending Closed Classes

Extending Closed Classes

There’s one last twist to working with classes in .NET: extension methods. EXTENSION METHODS behave as though they were standard instance methods, but they’re defined in a separate module They allow you to add new methods to a class without recompiling or inheriting from it, so you can extend the functionality of sealed classes and classes, like those in the BCL, that you can’t or shouldn’t change directly. Let’s look at how they work:

1 Create a Public Module class to contain the methods.

2 Import the System.Runtime.CompilerServices namespace.

3 Mark each method with the <Extension()> attribute and declare it Public:

<Extension()>
Public Sub MyMethod...

4 The first parameter of the method must be the name of the type the method extends. You don’t actually pass this argument to the method when you call it.


  

You are currently reading a PREVIEW of this book.

                                                                                        

Get instant access to over
$1 million worth of books and videos.

  

Start a Free Trial