Skip navigation links
Home
Document Center
Blog
Videos
Forum
PhillyXAML.org > Blog > Posts > Overview of Extension Methods
Overview of Extension Methods
Extension Methods allow us to extend existing objects without having access to the original source code or assemblies for those objects. We can add new methods to existing classes to give us enhanced functionality without having to reinvent the wheel when an existing class already posesses all of the functionality we want to encapsulate. One thing to be aware of is that you cannot extend static classes like the System.Math class for example.
 
One example of an extension method might be if we wished to extend the Control class to provide a simple method for setting the Background property by simply passing in a Color. After we create our extension methods, we can simply use them as we would any method written into the original object. We could then call something like myControl.SetBG(Colors.Blue) which will then create a blue SolidColorBrush and assign it as the background brush.
 
The first step in creating this example will be to create a new class in an existing project, or create an Extension Method Library, like we will be doing in the Extending FrameworkElement series and create a new class. After we have the class file open, we want to mark our class as static.
 
When we create extension methods, we declare them as normal. The difference is that the first argument must be the type you are trying to extend, preceded by the this keyword. We can then use that local variable from within our method to access the specific instance of the object we are extending.
 
using System.Windows.Media;
using System.Windows.Controls;

namespace PX.Samples.FrameworkElementExtender
{
    public static class TestExtender
    {
        public static void SetBG(this Control elUI, Color brushColor)
        {
            elUI.Background = new SolidColorBrush(brushColor);
        }
    }
}
 
We can then do this from code:
private void button3_Click(object sender, RoutedEventArgs e)
{
    this.SetBG(Colors.Gold);
}

Comments

There are no comments yet for this post.