22. June 2011 18:23
Many people are not aware of this. It is possible since .NET 3.5 to extend any class in c# to make it appear that extra functions have been added to a class. Here is a short example of being able to add an extra function to the bool class / type that exists in c#
public static class ExtenderBool
{
public static string ToHuman(this bool b)
{
if (b)
return "Yes";
return "No";
}
}
You can then use this in c# so long as the namespace is in scope from the calling function. Here is a quick example of a program to test it.
class Program
{
static void Main(string[] args)
{
bool tmp = true;
Console.WriteLine("Value: {0}", tmp.ToHuman());
Console.ReadLine();
}
}
The above works because the compiler will figure out that you want it to be able to use the function with that class as a argument to the static function though It does not actually add it to the class it self.
8ccff3b5-dfec-49f2-b01e-25dd31222326|0|.0
By: james
Category: C#
Tags: c#, class, extend class