0

I just stumbled over the following:

class AFrameworkElement : FrameworkElement
{
    private void SomeMethod() 
    {
        Size s = new Size {
            Width = Height = 10
        };
        // the size isn't used for measuring oder arranging
    }
}

Suddenly I was unable to resize the Control... IntelliSense showed the problem: I put he mouse over Height and it showed that the FrameworkElement.Height property was meant. So why is it impossible to use double assignements in object initializers?

HerpDerpington
  • 3,751
  • 4
  • 27
  • 43
  • 2
    You can't reference members from the object being initialized from inside the initializer. – Federico Berasategui Aug 22 '13 at 16:07
  • 1
    I voted to close because that's just the way it is. Not much way to answer this besides to say, "Yep, that's the way it is, and here's the part of the spec that says so." The workaround is trivial: `Width = 10, Height = 10`. – Tim S. Aug 22 '13 at 16:09

1 Answers1

2

In an object initializer expression the object itself is not accessible within the initialization expression. Anything used in that expression is interpreted as if it were used outside the object initializer. Hence in this case Height = 10 is evaluated within the context of AFrameworkElement and Height binds to a property on that object

JaredPar
  • 733,204
  • 149
  • 1,241
  • 1,454