find and solve || findandsolve.com
Please wait.....

Extension methods in C#


Extension methods,introduced in C# 2008,allow you to extend a class without deriving a new class from that class. The behavior of extension methods is similar to that of static methods and they are also defined with the static keyword.An extension method can be defined in a static class. The first parameter of an extension method is of type that the extension method extends and it is preceded by the this keyword,as shown in the following code snippet:

using System;
namespace extensionMethods
{
public static class MyClass
  {
       public static int MyExtensionMethod(this string number)
       {
return Int32.Parse(number);
       }
  }
public class Program
{
public static void Main()
{
int num1=200;
int num2;
int result;
string x="300";
num2=x.MyExtensionMethod();
result=num1+num2;
Console.WriteLine("Result ="+result);
Console.ReadLine();
}
    }
}

The first given above code snippet shows the definition of a static class,MyClass. In the MyClass class,we have defined an extension method,MyExtensionMethod,which extends the string type.The MyExtensionMethod method takes a string type parameter converts it into an equivalent integer value,and returns the integer value.You can notice that the this keyword is used before the parameter list of the MyExtensionMethod method.


In the second code snippet,we have declared three int type variables,num1,num2, and result,and assigned the value 200 to num1.After that ,we have declared a string type variable,x,and assigned it the value 300.Next,we have called the extension method,MyExtensionMethod,by using the string variable,x.The Extension Method method converts the value stored in the x variable to an equivalent integer value and returns the resultant value.We have stored the value returned by the MyExtensionMethod method in the num2 variable. After that,we have added the values stored in the displayed the value stored in the result variable.




Sundar  Neupane

Sundar Neupane

I like working on projects with a team that cares about creating beautiful and usable interfaces.

Comments



Report Response