Extension Methods in C#


Extension methods are static methods, which are called as if they were instance methods on the extended type. With Extension methods, you can add methods to existing types without even creating a new derived type, recompiling, or modifying the original type.

The following is the extension method we have created.

public static int myExtensionMethod(this string str) {
   return Int32.Parse(str);
}

Let us see an example wherein we have used extension method.

Example

 Live Demo

using System;
using System.Text;
namespace Program {
   public static class Demo {
      public static int myExtensionMethod(this string str) {
         return Int32.Parse(str);
      }
   }
   class Program {
      static void Main(string[] args) {
         string str1 = "565";
         int n = str1.myExtensionMethod();
         Console.WriteLine("Result: {0}", n);
         Console.ReadLine();
      }
   }
}

Output

Result: 565

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 23-Jun-2020

621 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements