C#

Examples of Extension Methods in C#

In this post on Examples of Extension Methods in C#, I will explain the concept of extension methods in C# using several examples. Before getting started with examples let us first understand the extension methods. In fact, extension methods make it possible to add in the existing functionality. In other words, suppose we already have a library class with us. Basically, extension methods allow us to add our own methods in that class. The extension method gets added after the original type is compiled.

Examples of Extension Methods in C#

To begin with, let us create a simple function in C# that converts a string to another string with all characters in the upper case. In this case, we add this function as an extension method to the String type.

using System;
namespace ExtensionMethodsDemo
{
    public static class MyClass
    {
        public static string getUpper(this String s)
        {
            return s.ToUpper();
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            String s1 = "hello, world!";
            String s2 = s1.getUpper();
            Console.WriteLine($"s1={s1}, s2={s2}");
        }
    }
}

Output

An Example of extension Method in C#
An Example of extension Method in C#

As you can see in the above code, we create the method as static. However, we call it with the instance of String class using the instance method syntax.

Given these points, let us create another extension method that we will use to find whether a triangle is valid or not. Therefore, we create an extension method with the name isValid() for the type Int32 as shown below.

 public static class MyClass1
    {
        public static bool isValid(this int a, int b, int c)
        {
            return a < (b + c);
        }
    }

After that, we use this method to find out whether the values entered for the three sides of a triangle form a valid triangle or not. Also, note the symbol of the extension method as shown in the following figure.

An Extension Method
An Extension Method

The complete code is given below.

using System;
namespace ExtensionMethodsDemo
{
    public static class MyClass1
    {
        public static bool isValid(this int a, int b, int c)
        {
            return a < (b + c);
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int a, b, c;
            a = 100;
            b = 25;
            c = 35;
            bool b1 = a.isValid(b, c);
            bool b2 = b.isValid(a, c);
            bool b3 = c.isValid(a, b);
            if (b1 && b2 && b3)
                Console.WriteLine("Triangle is valid");
            else
                Console.WriteLine("Triangle is not valid");
        }
    }
}

Output

An Extension Method for the Type Int32
An Extension Method for the Type Int32

Important Points Regarding Extension Methods

  1. We define extension methods in a static class.
  2. These methods are created at static methods.
  3. However, they are called with an instance method syntax.
  4. Also, the extension methods don’t override any existing method of a type.
  5. Whenever creating a derived type is not possible, we can create and use extension methods. For instance, with sealed classes, it is still possible to achieve reusability with the help of extension methods,
  6. Extension methods can have other parameters also. However, the first parameter should always be of the type to which we want to add the extension method.
  7. Additionally, the first parameter should be proceeded by this keyword.

Summary

In this article on Examples of Extension Methods in C#, I have explained the concept of extension methods in C# with few examples. In fact, we can create extension methods for any existing type. Particularly, they are useful when inheriting a type is not possible.


You may also like...

Leave a Reply

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