Extension Method

There are some cases where we want to add methods to some sealed classes, or classes from other libraries. In some languages, this is not possible, but in C#, we can use extension methods.

For example, here, we have the Student class from another library, the code cannot be edited. We want to add Print method.

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}

We create an extension class, this class must be static, and the method must also be static, and the first params passed in is the class that needs an extension, with the keyword this.

public static class StudentExtension
{
   public static void Print(this Student student)
   {
      Console.WriteLine(student.ToString());
   }
}
 
var student = new Student();
student.Print();

Last updated