Extension methods : how to add more Extra methods to type String, Int or ... very easily ?

Mar 17 2012

You can actually "add" methods to existing types very easily even without creating a new derived type. This is exreamly cool fast and time to times it comes in handy. I am going to tell you very simply othrwise you can read the official supper correct version on MSDN. 

Assume we have a string like this:

string myString = "Hello! ";

Then normally we can have some string type methods like 


But how about if we want to have our own methods in this type for example
that for example returns 
"Hello! Cool" 

Ok to make this simple menu we need to make a class 

namespace ExtensionMethods
    public static class MyExtensions
// to be exteamly simple we just add word "Cool" to the end of string I am sure you can  
// develop it  yourself 

        public static string addCool(this string str)
            return  str+"Cool" ;

And then add the name space to the classes we we want to have our extra methods in :
(Where we are programming our main program , it could be a webform code behind  for example )
using ExtensionMethods;

Then try:
string myString = "Hello! "; 
string my2ndstring = myString.AddCool(); 

You can see the value of my2ndstring would be "Hello! Cool"

Wasn't it really cool and simple, you can do the same with int,Datetime or what ever types you want to. the secret lies in public static string addCool(this string str) . It is a static method and has a this string as one of its arguments. Of course you can add more arguments and make a more useful method anyway ! 

Privacy Statement Terms Of Use Copyright 2011 by Rooznamechi