Extension methods are gonna be fun!

So I've had a (very) small amount of time to play around with Orcas and Silverlight, but some of the C# 3.0 features are going to come in handy. Greg Schechter has already written about using object initializers with XAML objects and back in March Scott Guthrie showed an example of extension methods. I've already come up with a nice little use for the latter.

Because of its declarative nature, there are some properties you can set quite easily inside XAML, but not so easily in C# — specifying the Canvas position for an object is one of those.

<Rectangle Canvas.Left="100" Canvas.Top="50" Width="10" Height="10/>

Rectangle r = new Rectangle();
r.SetProperty<double>(Canvas.Left, 100);
<double>(Canvas.Top, 50);

Here's a nice little way object extensions can simplify your life.

public static class SilverlightExtensions
public static void SetCanvasPosition(this Visual v, double left, double top)
v.SetValue<double>(Canvas.LeftProperty, left);
<double>(Canvas.TopProperty, top);

Because I need to be able to create a ton of Rectangles programmatically, I can replace the two earlier lines of code with one

r.SetCanvasPosition(100, 50);

Comments (5)
  1. I’m looking forward to being able to write something like:

    DateTime d = 24.Hours().Ago();

    What a pity there isn’t such thing as Extension Properties so we could get rid of the parentheses too! 🙂

  2. Casper says:

    Technically, there’s nothing stopping you from writing the following, although I question its usefulness 🙂

    DateTime d = 24.HoursAgo();

    public static DateTime HoursAgo(this int value)


     return DateTime.Now.Subtract(new TimeSpan(value, 0, 0));


    and if you had an enum, you could easily get

    DateTime d = 3.Ago(Minutes);

    although the second would look a bit weird 🙂

  3. Yeah, but you must admit that


    doesn’t read as nicely as


    The fact that you can only do methods rather than properties menas you’re stuck with the parentheses.

  4. Casper says:

    True. I’m not claiming these extensions are the be-all and end-all of the language though, just a nice addition 🙂 Baby steps …

  5. billie says:

    These really break the OO clarity that c# has.

Comments are closed.

Skip to main content