Extension method is an very useful method to the developer. It will extend the methods of an existing class. That is we are regularly using the string methods like
1.ToLower
2.Toupper
string s="sugunthan";
string upper=s.ToUpper();
Like this way I want to reverse my string by using an method
Using older method
class Program
{
static void Main(string[] args)
{
string s = "sugunthan";
stringmethod sm = new stringmethod();
string reverse = sm.Reverse(s);
Console.WriteLine(reverse);
}
}
class stringmethod
{
public string Reverse(string source)
{
string n = string.Empty;
int size = source.Length;
size = size - 1;
for (int i = size; i >= 0; i--)
n = n + source[i];
return n;
}
}
In this classic approach we must create an object for the class and call the function by using that class.
Instead this old way we will using the extension method
The advantages are
1. Use as like other build in string methods i.e with intelligence
2. Able use with the constant like "sugunthan".Reverse();
3. Dont bother about the parameter type.
Example
using MyExtensionMethods;
namespace extension_methods
{
class Program
{
static void Main(string[] args)
{
string s = "sugunthan";
string reverse = s.Reverse();
Console.WriteLine(reverse);
Console.WriteLine("extension method".Reverse());
}
}
namespace MyExtensionMethods
{
public static class MyExtension
{
public static string Reverse(this string source)
{
string n=string.Empty;
int size = source.Length;
size = size - 1;
for (int i = size; i >= 0; i--)
n = n + source[i];
return n;
}
}
}
1.ToLower
2.Toupper
string s="sugunthan";
string upper=s.ToUpper();
Like this way I want to reverse my string by using an method
Using older method
class Program
{
static void Main(string[] args)
{
string s = "sugunthan";
stringmethod sm = new stringmethod();
string reverse = sm.Reverse(s);
Console.WriteLine(reverse);
}
}
class stringmethod
{
public string Reverse(string source)
{
string n = string.Empty;
int size = source.Length;
size = size - 1;
for (int i = size; i >= 0; i--)
n = n + source[i];
return n;
}
}
In this classic approach we must create an object for the class and call the function by using that class.
Instead this old way we will using the extension method
The advantages are
1. Use as like other build in string methods i.e with intelligence
2. Able use with the constant like "sugunthan".Reverse();
3. Dont bother about the parameter type.
Example
using MyExtensionMethods;
namespace extension_methods
{
class Program
{
static void Main(string[] args)
{
string s = "sugunthan";
string reverse = s.Reverse();
Console.WriteLine(reverse);
Console.WriteLine("extension method".Reverse());
}
}
}
namespace MyExtensionMethods
{
public static class MyExtension
{
public static string Reverse(this string source)
{
string n=string.Empty;
int size = source.Length;
size = size - 1;
for (int i = size; i >= 0; i--)
n = n + source[i];
return n;
}
}
}
No comments:
Post a Comment