Powered by Blogger.

Saturday, March 1, 2014

Extension method in MVC

Here we will discuss about an important concept i.e Extension method in MVC. Also you can check out my previous topics on: Asp.Net MVC4 Controller class example, Ajax interview questions and answers and Exception handling in C#.Net.

This is a kind of method which will extend the method of 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)

Also you can check out:

- Body onload function in content page in asp.net

- Readonly textbox value lost on postback asp.net

- Set maximum length for multiline textbox in Asp.Net

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.
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.