Extension Methods - C# Tutorial
C# Course / Version Features / Extension Methods

Extension Methods

BLUF: Mastering Extension Methods is essential for building robust applications with the .NET ecosystem. This tutorial provides clear explanations and practical examples to help you understand and apply this C# concept.
Enterprise Development Tip: Extension Methods

C# is a powerful, modern language for enterprise solutions. Discover how Extension Methods enhances your development workflow in the guide below.

C# provides the capability to define and append new methods to an already existing class without the need to create a separate subclass. This process does not necessitate the recompilation of the original class. C# extension methods represent a unique category of static methods that are callable as if they were 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 this illustration, we will be incorporating an extension method named GetUpperCase within the String class in C#.

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 this instance, we are incorporating an extension method into 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:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience