Global Variables in C#.net

decrypt

Junior Contributor
Joined
Oct 6, 2003
Messages
216
This should hopefully be an easy question to answer. Basically what I want to know how to do, is how to create an object that can be accessed in any class in the project without having to actually pass it into every single class.

At the moment I'm creating the object in the main form and then passing that object into a class' constructer. When I have one thing that keeps getting passed into a bunch of classes it starts to get confusing. Is there something like an include file in c#.net so that I could just define it in there and use it throughout the project? Is there an easier way to do this?
 
You could declare the methods / properties as static ( C# 2.0 the class itself could be declared static) - this would result in only a single instance being allocated in memory.
 
But how could I access that object from anywhere in the project once it's created? Would making the object static allow me to do this?

Say I create a string in the main form and I have about 5 classes in the project. How could I make it so that that string could be accessed from anywhere in the project without having to pass it or it's parent into all of the classes? Is there a way to sort of do something like this:

Form 1:
Code:
global string gHello;
gHello = "test";

Class 1:
Code:
MessageBox.Show(gHello); //outputs test

I'm trying to ask this as simply as possible using a string. I guess I'm sort of going away from object-oriented programming. I could live without the luxury of being able to do this if it's not possible. It's just it would make things a lot easier if it is.
 
It might be better to rethink your approach, if the string is part of the form then why would the other classes need access to it?

It might help if you gave a little more detail about why you need this as there may be an alternate solution.
 
Thanks for the link, I finally understand how statics work and it's just what I was looking for :P
 
Back
Top