Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to reference a certain variable throughout the namespace?

I have a mainForm variable that is used nearly everywhere in my program. I'd like to be able to reference to this variable without having to type the name of the class that holds this variable (i.e. instead of Global._mainForm, I should be able to just type _mainForm to access this variable anywhere within the same namespace).

What is the best way to accomplish this?

like image 815
l46kok Avatar asked Jan 30 '26 10:01

l46kok


1 Answers

Anytime I see a global anything I get worried, so I would reconsider how your program is architected. You can almost always get away without having a globally accessible object. Although there are legitimate reasons to have a globally accessible object, usually I try to stay away from them.

From the little information you've given, you might be able to use events to talk to the main window instead of directly accessing it.

If you do have real need for a globally accessible object then you could do something like this

Note: In the code below everything is static, conversely you could create a special static class that holds a reference to the instance of the class you're really interested in. But there is no way that I'm aware of to hold a global reference that is outside of all namespaces to an instance of an object.

using Bar = ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot.TestClass;

namespace ProbablyAReallyBadIdeaToHaveAGlobalAnythingButHeyWhyNot
{
  public static class TestClass
  {
    public static int TestFoo { get; set; }
  }
}

namespace Foo.SomeOtherNamespace
{
  class MyClassThatDoesStuff
  {
    public void DoStuff()
    {
      Bar.TestFoo = 123;
    }
  }
}
like image 112
Zipper Avatar answered Feb 02 '26 02:02

Zipper