Tuesday, December 14, 2010

ValueTypes cannot be modified by extension methods

I was converting a WPF code to silverlight when I noticced that Silverlight does not have the Offset Member method to the point structure. I thought I could get away with a dead simple extension method :

namespace ConsoleApp 
{ 

    public static class SlUtils
    { 
        public static void OffsetSL(this System.Windows.Point p, double CenterX, double CenterY)
        { 
            p.X += CenterX; 
            p.Y += CenterY; 
            // p = new System.Windows.Point(p.X, p.Y); does not help either
        } 
    } 

    class Program 
    { 
        static void Main(string[] args) 
        { 
            System.Windows.Point p = new System.Windows.Point(0, 0);
            p.OffsetSL(10, 20);
            Console.WriteLine("{0},{1}", p.X, p.Y); // prints {0,0} // FAIL 
            p.Offset(10, 20);
            Console.WriteLine("{0},{1}", p.X, p.Y); // prints {10,20} 
            Console.ReadKey(); 
        } 
    } 
} 
I was so wrong :) The extension method cannot modify a value type. What you can do is return from an extension method (instead of void) the value you want... ah well you can't have Everything.

Enjoy!

No comments:

Post a Comment