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:-
{
public static class Extensionclass
{
{
return Int32.Parse(str);
}
{
{
}
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();
}
}
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:
Post a Comment