Is it possible to use global variable/function in VC.NET?

  • Thread starter Thread starter Eddie
  • Start date Start date
E

Eddie

I found it's not possible.

But if I have a function which is called by every forms,
do I have to copy the function to every form class?
It looks like non-sense.

Is there any other options?
 
Eddie said:
Ok, I got it.
Inheritance is a good choice here.
No, I don' think so. Better put your utility function as a static
member function in an "Utils" (name it the way you want) class.

Arnaud
MVP - VC
 
Actually, I added static member function for BaseForm which is inherited
from System::Windows::Forms::Form.
And all other forms are inherited from the BaseForm.
Then I can type following code when I need the function.

utility_function(...);

But if I create a specific utility class like

public ref class Utils {
....
public: int utility_function();
....
};

Whenever I try to use the funtion, I have to write the following code.

Utils utils; (or Utils^ utils = gcnew Utils();)
utils->utility_function();

I think this is not cute code. ;-P

Sorry.
I'm a quite newbie in VC.NET so I think I can be missing some other way.
Please give me one more comment on this.
I have a lot of forms for my project, so I think it's also not cute that
I have to
change all base forms.
 
Eddie said:
public ref class Utils {
...
public: int utility_function();
...
};

As Arnaud recommended, make your methods static:

public:
static int utility_function();
Whenever I try to use the funtion, I have to write the following code.

Utils utils; (or Utils^ utils = gcnew Utils();)
utils->utility_function();

I think this is not cute code. ;-P

Once you make the method static, you don't have to create an instance,
you can simply type

Utils::utility_function();

In this case Utils looks like a namespace and utility_function appears
to be a non-member function in that namespace. That's how you handle it
in .NET, because you don't have a choice to write non-member functions.

Your next question may be how to handle non-member (global) constants in
..NET. In native C++ you just write

const int MyConst = 10;

In .NET you make it a static property. Here's an example:

public ref class Utils
{
public: static property int MyConst
{
int get() { return 10; }
}
};

And use it like this: Utils::MyConst.

Tom
 
Back
Top