Extension
methods enable you to "add" methods to existing types without
creating a new derived type, recompiling, or otherwise modifying the original
type. Extension methods are a special kind of static method, but they are
called as if they were instance methods on the extended type. For client code
written in C# and Visual Basic, there is no apparent difference between calling
an extension method and the methods that are actually defined in a type.
Extension
methods can be used in any type of projects like ASP.Net, MVC, Windows Forms,
and WPF etc.
Implementation:
Create a class
with some desired name and place it in any place of the project. Make sure the namespace of the class should
be the root namespace of the project.
Create a static method which a return type and a parameter. The parameter should be prefixed with “this”
keyword.
Usage:
If any variable
that matches with the parameter type of the extension can use the extension
methods. Intelligence will invoke the
list of extension methods implemented with that variable type.
Example:
This example is
done in an MVC project.
Create a class
with name “ExtensionMethods” as below and place it in the root of the project
or in any folder.
using System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
namespace
ExtensionMethodsDemo
{
public static class ExtensionMethods
{
public static bool
IsValid(this string str)
{
if
(str.Contains("john"))
return true;
else
return false;
}
}
}
Now extension
method is created with the name “IsValid”, return type as “bool” and parameter
type as string. This extension will
return true if the parameter contains the string “john” or it will return
false.
For using the
above extension method, go to a controller; create a string with some
content. Now if we want to check if the
string contains the phrase “john”, it’s enough to call the method as below.
string name = "John
Player";
if(name.IsValid())
{
//some stuff
}
else
{
//some stuff
}
This is the way
of calling the extension method.
Extension
methods are very improvement for creating common validations and string
formations for a project.
No comments:
Post a Comment