Extension Methods

C# allows us to create and add new methods to existing class without creating a new child class. The existing class does not require recompiling the code. C# extension methods are the special type of the static methods that can be called as instance methods.

We can add extension methods in both C# predefined classes and user created custom classes. We need to consider the following points to define an extension method.

  • An extension method should be a static method.
  • It must have this keyword associate with class name.
  • The class name should be the first parameter in the parameter list.

In the following example, we are adding an extension method GetUpperCase in C# String class.

C# Extension Methods Example 1

Example

using System;
namespace CSharpFeatures
{
    public static class StringHelper
    {
        public static string GetUpperCase(this string name)
        {
            return name.ToUpper();
        }
    }
    public class ExtensionMethodExample
    {
        static string name = "Hello World";
        static void Main(string[] args)
        {
            string str = name.GetUpperCase();  // calling extension method using string instance 
            Console.WriteLine(str);
        }
    }
}

Output

Output

HELLO WORLD

C# Extension Methods Example 2

In the following example, we are adding extension method to a Student class.

Example

using System;
namespace CSharpFeatures
{
    public static class StudentHelper
    {
        public static string GetUpperName(this Student student) // Using this before Student class
        {
            return student.name.ToUpper();
        }
    }
    public class Student
    {
        public string name = "Hello World";
        public string GetName()
        {
            return this.name;
        }
    }
    public class ExtensionMethodExample
    {
        static void Main(string[] args)
        {
            Student student = new Student();
            Console.WriteLine(student.GetName());
            Console.WriteLine(student.GetUpperName());
        }
    }
}

Output

Output

hello world
HELLO WORLD

Input Required

This code uses input(). Please provide values below: