Extension method in MVC

Check out Best Alternative to InfoPath


Here we will discuss an important concept i.e Extension method in MVC. Also, you can check out my previous topics on Asp.Net MVC4 Controller class example,Asp.Net interview questions and answers in Lotex Business Solutions and Exception handling in C#.Net.
This is a kind of method which will extend the method of a class with out touching the base class as well as with out inheritance.
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.
Syntax: static <return type> Functionname(this classname  obj)
For example: There are two modules A and B. In side the Module A there is Class A and Inside
Module B, there is  class B.In Class A there are method 1(),Method 2(),Method 3() and one newly introduced method i.e Add().
So our aim here is to use the newly introduced method Add() from Class A inside the class B in Module B.
Module A
\\\\
Class A
\\\\\
Method 1()
Method 2()
Method 3()
Add()-> Newly introduced method in Class A and Let us assume it is a string type.
Now our aim is to use the newly introduced method Add() in Class B of Module B. So we can use as follows.
Module B
\\\\
Class B
\\\\\
static string Add(this A obj)
Here A is the class name.
the string is the return type.
obj is the object for the respective class A.
Note: You need to add the reference for the respective class from which you are using the method.
Benefits of Extension methods:
1- Extension methods allow existing classes to be extended without depending on inheritance or having to change the class’s source code.
2- If the class is sealed then there is no concept of extending its functionality. For this a new concept is introduced i.e. extension methods.
3- This feature is important for all developers.
Some important tips while using Extension methods:
1- You should define extension method in a top-level static class.
2- The extension method with the same name and signature as an instance method will not be called.
3- Extension methods cannot be used to override existing methods.

You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →