Using this technique you can add methods to existing types. Say you want a method in the type string which returns the characters in the string in the reverse order
You could probably
1>Inherit from the class System.String, (suppose you called this inherited class as MyStringExtension )add the new method called Reverse() to the inherited class. Then declare a variable of the type MyStringExtension instead of declaring it a string. Then call the method Reverse() on it.
OR
2>Take the faster route and declare an extension method on the type string.
In the code below I have declared an extension method on the type string, that just returns the string "Dilbert" when called.
You could probably
1>Inherit from the class System.String, (suppose you called this inherited class as MyStringExtension )add the new method called Reverse() to the inherited class. Then declare a variable of the type MyStringExtension instead of declaring it a string. Then call the method Reverse() on it.
OR
2>Take the faster route and declare an extension method on the type string.
In the code below I have declared an extension method on the type string, that just returns the string "Dilbert" when called.
Adding an extension method to the type string
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodExample
{
class Program
{
static void Main(string[] args)
{
string s="";
//Here ReplaceDilbert() is an extension method on the type string
//Here ReplaceDilbert() is an extension method on the type string
Console.WriteLine(s.ReplaceDilbert());
//Displays Dilbert
}
}
static class StringExtension
{
//This method must be static
public static string ReplaceDilbert(this string s)//notice there is a this keyword
{
return "Dilbert";
}
}
}
Adding an extension method to the type float
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExtensionMethodExample
{
class Program
{
static void Main(string[] args)
{
float f= 10;
Console.WriteLine(f.GetInverse());
//Displays 0.1
}
}
//This class must be static
static class StringExtension
{
//This method must be static
public static float GetInverse(this float f)//notice there is a this keyword
{
return 1 / f;
}
}
}
You can define your extension method in a different class or namespace, just make sure that it (the class and namespace containing the extension method) is accessible to the calling code.
No comments:
Post a Comment
Comments will appear once they have been approved by the moderator