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
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
HELLO WORLD
C# Extension Methods Example 2
In this instance, we are incorporating an extension method into a Student class.
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
hello world
HELLO WORLD