We are providing online training of realtime Live project on Asp.Net MVC with Angular and Web API. For more information click here. If you have any query then drop the messase in CONTACT FORM

Friday, April 10, 2015

Extension method
------------------------------------------------------------
 

An extension method represents static methods as instance methods. It must be located in a static class. In extension method "this" keyword is used with the first parameter and the type of the first parameter will be the type that is extended by extension method.
 
Example:-
 
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

namespace StringToInteger

 
{
 
public static class Extensionclass
{
public static int extensionMethod(this string str)
 
{
return Int32.Parse(str);
 
}
}
class Program
{
static void Main(string[] args)
 
{
string str = "123456789";
int num = str.extensionMethod();
Console.WriteLine("The output using extension method: {0}", num);
Console.ReadLine();
 
}
}
}
 
Example:- convert to first latter of given string to upper latter
 
namespace FirstToUpper{  public static class Extensionclass
{

   public static string UppercaseFirstLetter(this string value) {if (value.Length > 0)
 {

  char[] array = value.ToCharArray();
     array[0] = char.ToUpper(array[0]);
   return new string(array);
}
 return value;}
}class Program{ static void Main(){ string value = "mithilesh kumar singh";
value = value.UppercaseFirstLetter();
Console.WriteLine(value);
Console.ReadLine();
}
}

}
Output
 
Mithilesh kumar singh
 

 NOTE:
 
-> An extension method is defined as static method but it is called like as instance method.
->An extension method first parameter specifies the type of the extended object, and it is preceded by the "this" keyword.
->An extension method having the same name and signature like as an instance method will never be called since it has low priority than instance method.
->An extension method couldn't override the existing instance methods.
->An extension method cannot be used with fields, properties or events.
->The compiler doesn't cause an error if two extension methods with same name and signature are defined in two different namespaces and these namespaces are included in same class file using directives. Compiler will cause an error if you will try to call one of them extension method.

 



 
 


 

 

No comments: