Example:
public static class Extensions
{
public static int ToInt32Ext(this string s) // we add the this word
{
return Int32.Parse(s);
}
public static int ToInt32(string s)
{
return Int32.Parse(s);
}
}
void Main()
{
string s = "5";
int x = s.ToInt32Ext(); // using the extension method
Console.WriteLine(x);
x = Extensions.ToInt32(s);
Console.WriteLine(x);
}
Please notice:
- The this word must be the first argument in the method,in this example we only have one argument but if you have more remember that it must be the first thing.
- The class must be a static class.
No comments:
Post a Comment