This post has been migrated from www.experimentsincode.com, we apologise if some of the images or content is missing

This post has been migrated, original date 24 Sep 2008 I am going to start blogging extension methods that I think are useful. The onesI have detailed below are very simple but I think they make code more readable andquicker to write. The first is to do with passing in objects to have them formatted in the outputtext. The standard way to do this is:
12        string name = "mike"; 13        int age = 25; 14        string text = "Hello{0}, You are {1} years old"; 15 16        Console.WriteLine(string.Format(text,name, age));
I don't like this, why should I have to use a static method on the string type?Why can't this be a method on the instance of the string? So I created an extensionfunction to do this:
26        public staticstring Params(thisstring text, paramsobject[] args) 27        { 28            return string.Format(text, args); 29        }
And now I can do the same as above but swap out line 16 for:
18        Console.WriteLine(text.Params(name, age));
The second one I find useful is for casting objects to a different types. Take forexample the following code example where I have an interface and a concrete class:
38     public interfaceICalc 39     { 40        int Add(inta, int b); 41     } 42 43     public class Calc : ICalc 44     { 45        public stringCalcName { get { return"My Calc"; } } 46 47        #region ICalc Members 48 49        public intAdd(int a, intb) 50        { 51            return a + b; 52        } 53 54        #endregion 55     }
I create an instance of the concrete class like so:
20            ICalc myCalc = new Calc();
Say for some reason (there could be many) I need to access the CalcName propertythat is not defined in the interface, this means I need to cast my current instanceto the concrete type. This would normally be done like so:
23            ((Calc)myCalc).CalcName;
This to me is not a nice solution. So I created this extension function:
35         public static T AsType<T>(this object obj) 36         { 37             return (T) obj; 38         }
Now I can do the same as above but like so:
21             myCalc.AsType<Calc>().CalcName;
The joy of extension method is that even simple ones can make coding quicker and easier to read. Let me know if you have some useful extension functions that I could make use of.
comments powered by Disqus