C#

Examples of Extension Methods in C#

Programmingempire

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.


Further Reading

Selection Sort in C#

Insertion Sort in C#

Bubble Sort in C#

How to Create Instance Variables and Class Variables in Python

Comparing Rows of Two Tables with ADO.NET

Example of Label and Textbox Control in ASP.NET

One Dimensional and Two Dimensuonal Indexers in C#

Private and Static Constructors in C#

Methods of Array Class

Anonymous Functions in C#

Programs to Find Armstrong Numbers in C#

Matrix Multiplication in C#

One Dimensional and Two Dimensional Indexers in C#

Static Class Example in C#

Rotating an Array in C#

Generic IList Interface and its Implementation in C#

Recursive Binary search in C#

C# Practice Questions

Creating Navigation Window Application Using WPF in C#

Find Intersection Using Arrays

An array of Objects and Object Initializer

Performing Set Operations in LINQ

Using Quantifiers in LINQ

Data Binding Using BulletedList Control

Grouping Queries in LINQ

Generic Binary Search in C#

Understanding the Quantifiers in LINQ

Join Operation using LINQ

Deferred Query Execution and Immediate Query Execution in LINQ

Examples of Query Operations using LINQ in C#

An array of Objects and Object Initializer

Language-Integrated Query (LINQ) in C#

How Data Binding Works in WPF

Examples of Connected and Disconnected Approach in ADO.NET

New Features in C# 9

IEnumerable and IEnumerator Interfaces

KeyValuePair and its Applications

C# Root Class – Object

Access Modifiers in C#

Learning Properties in C#

Learning All Class Members in C#

Examples of Extension Methods in C#

How to Setup a Connection with SQL Server Database in Visual Studio

Understanding the Concept of Nested Classes in C#

LINQ To SQL Examples

A Beginner’s Tutorial on WPF in C#

Explaining C# Records with Examples

Everything about Tuples in C# and When to Use?

Creating Jagged Arrays in C#

Linear Search and Binary search in C#

Learning Indexers in C#

Object Initializers in C#

Examples of Static Constructors in C#

When should We Use Private Constructors?

C# Basic Examples

IEqualityComparer Interface

programmingempire

You may also like...