C# Extension Methods

C# Code Snippets Extension Methods
Share:

About

In this code snippet, we will take a look at extension methods in C#.

If you have a class that you don’t own or is sealed you won’t be able to add anything to it. In such cases, you can use extension methods which will be “glued” on to the class. This enables you to add your code to a class without modifying it or creating a new derived class

Let’s have a look at the code below to see how to implement an extension method.

Code:

using System;

namespace ExtensionMethods
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass MC = new MyClass();

            //We can now call this method even though it isn't part of the MyClass.  
            MC.extensionMethod();

            Console.ReadLine();
        }
    }

    //Here we have a class thet we don't own or is sealed. 
    sealed class MyClass
    {
        public void writeText()
        {
            Console.WriteLine("This was written from the base class method.");
        }
    }

    //To be able to extend the above class we have to do the following:

    //Make this class static. 
    static class MyClassWithExtensionMethod
    {
        //Put the "this" keyword before the input parameter.
        //And make the input paremeter the type of the class that you want to extend. 
        public static void extensionMethod(this MyClass MC)
        {       
            //You can call methods from the base class if you need to.  
            //MC.writeText();

            Console.WriteLine("This was written from the extension method");
        }
    }
}

Resulting output:

Share:

Leave a Reply

Your email address will not be published. Required fields are marked *

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger