Namespace confusion using C++/CLI in Windows Forms Application

Go To StackoverFlow.com

2

I'm trying to save myself some coding time by taking advantage of using namespace in a Windows Forms project. I created a default Windows Forms project using C++/CLI in VS2010. I notice that the default namespaces that are imported are:

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

I want to create a DialogResult-typed variable, which (conveniently enough!) sits inside the System::Windows::Forms namespace. I go into the constructor for the default Form1 and add the line:

DialogResult dr;

I get the compiler error syntax error : missing ';' before identifier 'dr'.

However, if I change the line to either:

Windows::Forms::DialogResult dr;

or

System::Windows::Forms::DialogResult dr;

then everything works as expected.

I also tried adding

using namespace System::Windows;

and then

Forms::DialogResult dr

works too!

What am I missing about how these namespaces are working?! I'd like to avoid having to fully qualify all of the code I'm writing, but I can't figure out what it is I'm doing wrong since the namespace I need should already be imported.

2012-04-04 16:37
by aardvarkk


4

System::Windows::Forms::Form has a property named DialogResult, so inside of a Form subclass that property has scope precedence over the type in the global namespace.

I usually work around this with a typedef:

typedef System::Windows::Forms::DialogResult DialogResult_t;

Then any time you need to use the type, use DialogResult_t, and any time you need to access the property, use DialogResult.

Note that this issue is not C++/CLI specific – C++ has the same scoping rules and consequently would have the same problem; it's just that the .NET BCL reuses type names as property names quite extensively (where C++ code would avoid that) because C# does not have this issue.

2012-04-04 16:59
by ildjarn
Grr! I should have figured this one out, but great explanation and helpful advice! Thanks a lot - aardvarkk 2012-04-04 17:03
Ads