Freigeben über


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);
r.SetProperty<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);
      v.SetValue<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

  • Anonymous
    May 22, 2007
    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! :)
  • Anonymous
    May 23, 2007
    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 getDateTime d = 3.Ago(Minutes);although the second would look a bit weird :)
  • Anonymous
    June 02, 2007
    Yeah, but you must admit that24.HoursAgo()doesn't read as nicely as24.Hours.AgoThe fact that you can only do methods rather than properties menas you're stuck with the parentheses.
  • Anonymous
    June 02, 2007
    True. I'm not claiming these extensions are the be-all and end-all of the language though, just a nice addition :) Baby steps ...
  • Anonymous
    July 13, 2007
    These really break the OO clarity that c# has.