What is Extension method in C# ?
- An extension method is a special kind of
staticmethod that allows you to add new methods to existing types without creating derived types. - The extension methods are called as if they were instance methods from the extended type, For example:
xis an object fromintclass and we called it as an instance method inintclass. - An extension method is a static method of a static class, where the "this" modifier is applied to the first parameter. The type of the first parameter will be the type that is extended.
Example:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace LINQPractice.HelperClass
{
public static class String
{
public static string ConverToUpperCase(this string strg)
{
return strg.ToUpper();
}
}
}
Calling from Different class:
using System.Web.Mvc;
using LINQPractice.HelperClass;
namespace LINQPractice.Controllers
{
public class LINQController : Controller
{
// GET: LINQ
public ActionResult Index()
{
string str1= "vijay";
string outputstr= str1.ConverToUpperCase();
return View();
}
}
}
Important points for the use of extension methods:
- An extension method must be defined in a top-level static class.
- An extension method with the same name and signature as an instance method will not be called.
- Extension methods cannot be used to override existing methods.
- The concept of extension methods cannot be applied to fields, properties or events.
- Overuse of extension methods is not a good style of programming.
References:
https://www.codeproject.com/Articles/34209/Extension-Methods-in-C
http://www.c-sharpcorner.com/uploadfile/puranindia/extension-methods-in-C-Sharp-3-0/