Patrick
Patrick

Reputation: 23619

Why does instance.property.property not work in C#?

I have a strong C++ background and I'm just starting to use C#.

In a test application I write the following construction (wf is an instance of a class that I just wrote myself):

wf.m_button = new Button();
wf.m_button.FlatStyle = FlatStyle.System;

But the compiler (Visual C# Express 2008, using .Net 3.5) gives me this error:

'System.Windows.Forms.Control' does not contain a definition for 'FlatStyle' and no extension method 'FlatStyle' accepting a first argument of type 'System.Windows.Forms.Control' could be found (are you missing a using directive or an assembly reference?)

If I change the code to this:

Button button = new Button();
wf.m_button = button;
button.FlatStyle = FlatStyle.System;

This works.

Why is instance.property.property not allowed in C#, while in C++ you can easily write something like this:

myVariable->myDataMember->anotherDataMember = ...;

Upvotes: 0

Views: 126

Answers (2)

Vlad
Vlad

Reputation: 35584

As an addition to @Ed's answer: you could just write

wf.m_button = new Button() { FlatStyle = FlatStyle.System };

as well.

Upvotes: 2

Ed Swangren
Ed Swangren

Reputation: 124632

It has nothing to do with property chaining. You have declared m_button as a Control object, not a Button. The Control class does not expose a FlatStyle property. Even though you know that m_button is a Button under the covers, the compiler cannot determine that as you could assign anything to m_button that is an instance of a Control object or a descendant of the Control class.

Upvotes: 4

Related Questions