Extension Methods C# Help

There are many ways to extend a class. U you have the source for the class, then inheritance, which is covered in Chapter 4, is a great way to add functionality to your objects. What if the source code isn’t available? Extension methods can.help by allowing you to change a class without requiring the source code for the class.

Extension methods are static methods that can appear to be part of a class without actually being in the source code for the class: Let’s say that the Moneyclass from the previous example needs to have a
method AddToAmount(decimal amountToAdd). However, for whatever reason the original source for the assembly cannot be changed directly. All that you have to do is create a static class and add the AddToAmountmethod as a static method. Here is what the code would look-like:

Notice the parameters for the AddToAmountmethod. For an extension method, the first parameter is the type that is being extended preceded by the this keyword. This is what tells the compiler that this method is part of the Moneytype. In this example Moneyis the type that is being extended. In the extension method you have access to all the public methods and properties of the type being extended.

In the main program the AddToAmountmethod appears just as another method. The first parameter doesn’t appear, and you do not have to do anything with it. To use the new method, you make the call just like any other method:


Even though the extension method. is static, you use standard instance method syntax. Notice that we called AddToAmo~ntusing the cashl instance variable and not using the type name.

If the extension method has the same name as a method in the class, the extension method will never be called. Any instance methods already in the class take precedence.


This chapter examined C# syntax for declaring and manipulating objects. You have seen how to declare stalic and instance fields, properties, methods, and constructors. You have also seen that C# adds some new features not present in the OOP model of some other languages – for example, static constructors provide a means of initializing static fields, whereas structs allow you to define types that do not require the use of the managed heap, which could lead to performance gains. You have also seen how all types in C# derive ultimately from the type System. Object, which means that all types start with a basic set of useful methods, including ToString ().

Posted on October 28, 2015 in Objects and Types

Share the Story

Back to Top
Share This