Search⌘ K

Extension Methods

Discover how to use C# extension methods to add functionality to classes and structs without modifying source code or inheritance. Understand static classes, the this keyword, and how to extend sealed types.

Add functionality

There may be situations when we need to extend a class or struct’s functionality. There are several approaches we could take.

Change the source code

We could go to the source code of the type and make whatever changes we need. Consider the following Printer class. Its purpose is to print the Message property in a variety of ways. If we need additional functionality, we can simply add another method or edit existing ones: ...