C# - Extending any class or type

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.

E-mail Kick it! DZone it! del.icio.us Permalink


Comments (2) -

6/23/2011 2:21:53 AM #

these are called extention methods

msdn.microsoft.com/en-us/library/bb383977.aspx

Topper United States |

6/28/2011 5:25:36 AM #

Good start! Here is a little more detailed approach to writing Extension Methods
www.sexyselect.net/.../Writing-Extension-methods-Net

Nico United Kingdom |