Extension Methods
Explore how to extend existing classes and structs in C# using various techniques. Learn to update source code, use inheritance, and create extension methods to add new behaviors, especially when modifying sealed types or inaccessible source code. Understand the syntax and usage of extension methods and how they provide flexible solutions for enhancing functionality without altering original classes.
We'll cover the following...
We often need to extend the functionality of a class or struct. We can use several approaches depending on the type and our access to the source code.
Update 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.
Line 1: We declare a file-scoped namespace to organize our code without extra indentation.
Line 3: We define the
Printerclass.Lines 5–10: We define a property and a constructor to initialize the printer with a message.
Lines 13–16: We add a new method
PrintWithDashesdirectly to the class.
This approach is only useful if we control the source code of the type we want to modify. This isn’t possible in most cases ...