Extention Methods


Extention Methods
An extention method is a method that extends functionality of an existing class. So eaven if the class was written by someone else and is packageded so you can't modify it. You can still write your own functions that extend the class.

First you write an encapsulation class that holds the extention method. I will call it "Extentions", and it must be static!
namespace MyExtentions {
  public static class Extentions { }
}

Inside this class you can write as many extentions you want, but it's a good idea to bundle the extentions according to the class you extend. So that you only include relevant extentions through out the rest of your program.

Let's look at the syntax.
public static ReturnType FunctionName(this TypeToExtend objName) {} // Syntax

// Example
namespace MyExtentions {
  public static class Extentions {
    public static int AddOne(this int i){ return i+1; } // Example
  }
}

// Usage
int inTest = 2; // Create int and assign it as 2
int outTest = inTest.AddOne();
// Now inTest is 2, and outTest is 3.

It's verry straight forward and it's a verry usefull tool. Especialy if you have operations that you need to do allot. Eaven microsoft uses extention methods to extend there own framework! Linq as an example is "just" a set of extention methods that extends the IEnumerable types. (If you have not tryed Linq then learn it! It's simply just briliant)

-------

So now i think it's time to show you the power of extentions by providion you with a set of extention methods that you can use your self :-)

1. Color to int
Have you eaver tried to store a color in a file? or send it via sockets? or perhaps you just want to pass it to unmanaged code? That problem has happends to me... There are many solutions, but one of the most simple ones are to simply store the color code as an integer.
public static class ColorExtention {
      //8 bit red, 8 bit green, 8 bit blue.
      public static Color ToColor(this int iColor) {
        return Color.FromArgb(((byte)iColor), ((byte)(iColor >> 8)), ((byte)(iColor >> 16)));
      }

      //8 bit red, 8 bit green, 8 bit blue.
      public static int ToInt(this Color iColor) {
        return ((iColor.R) + (iColor.G << 8) + (iColor.B << 16));
      }
}

Using this extention you can convert from C# color to int and from int to C# color :-)
Just like this:
Color TestColor = Colors.Red;
int iColor = TestColor.ToInt();
iColor += 1578; // Change the color binary
Color NewColor = iColor.ToColor();

Nice trick right :-)

2. Lambda in thread.
Have you eaver needed a simple way to multi thread som work? Well theres a little thing called backgroundworker, but perhaps you are like me and want a simpler alternative...
public static class LambdaTriks {

    public static void RunInThread<T>(this Action<T> func, T data) {
      (new Thread(new ThreadStart(() => { func(data); }))).Start();
    }
}

using this extention method you can doo stuff like this:
Action<object> Func = (obj) => Console.WriteLine(obj.ToString());
Func.RunInThread(this);

In the above example i create a helper action, that writes an opbject to the console. Then in line 2 i use the extention method to create a new thread and run the action on that thread :-) Verry simple way to start actions in new threads.

3. Cross thread work.
Have you eaver had problems updating the GUI from a worker thread? Well here you can get a nice extention method that help you do GUI updates from worker threads.
public static class ControlExtensions
{
  public static void BeginInvoke(this Control Control, Action Action) {
    if (Control != null && Action != null && Control.IsHandleCreated)
      Control.BeginInvoke(Action);
  }
}

Using the extention you can write simple one liners that safely updates GUI from worker threads. The extention simply runs the action on the GUI thread :-)
// Imagine that "this" is a control with a lable called "lable"
Action<Control> Func = (obj) => {
  // This will be run from another thread.
  // If you update gui from another thread it will cast exceptions!

  // Using the new "BeginInvoke" extention method 
  // we can write lambda expressions that update gui from worker threads.
  obj.BeginInvoke(() => lable.Text = "Hej");
};

Func.RunInThread(this); // Start the "update" function from another thread

Now that's a nice extention method that have saved med tones of houers of debugging cross thread problems :-)

4. More lambda stuff.
Well this is a simple one. Dooing "foreach" statements on enumerable's like lists, using lambda's :-) Dooing for each is simple, but with this extention you can run lambda's on them.
public static class LambdaTriks {

  public static void ForEach<T>(this IEnumerable<T> source, Action<T> action) {
    if (source == null || action == null)
      return;
    foreach (T element in source)
      action(element);
  }
}

Usage:
// Start with a list
List<int> lst = new List<int>{2, 4, 6, 8};
// Without lambda for each
foreach(int i in lst) {
 Console.WriteLine("Int " + i.ToString());
}
// Using the lambda
lst.ForEach(i => Console.WriteLine("Int " + i.ToString()));

Saves a little code... But the most important thing to notice here is that using the lanbda we don't have to specify type because it uses generic's so you can change the type that the list contains without having the go through your code and change it in all foreach statements :-)

A nice trick that saves maitinance and code.


5. Sub Controls.
Have you eaver wanted to iterate all controls in a form and change a property? Say Enable all sub controls? or perhaps change background color of all controls? Heres a simple extention method that can help you. BUT BE AWARE! The function can cause perofrmance problems if you have lot's of controls!!!
using System.Linq; // The extention uses linq extention :-) Extentions using extentions. Nice...
public static class ControlExtensions
{
  public static IEnumerable<T> GetChildControls<T>(this Control Control) where T : Control
  {
    IEnumerable<T> childs = Control.Controls.OfType<T>();
    return childs.SelectMany(c => c.GetChildControls<T>()).Concat(childs);
  }
}

Now imagine you have a "FormMain" that contains all your Gui controls, but some of them are placed inside other gui controls. E.g. Some text bokses are placed inside a groupeBox.. The above control iterate them and find all sub controls :-)

You can now do stuf like:
// This will enable all sub controls :-)
this.Controls.GetChildControls().ForEach((ctrl) => ctrl.Enabled = true);

-----------

Now you should realy have a good ida about the power of extention methods :-) Feel free to use the extention methods for your self, but remember to give me credit! Click the "share" button in the top of the page and then you may use the code for free. :-)

And if you feel like helping then donate a littel money.
Any ammount eaven 1$ will be accepted.