Okay so I am working on a massive program involving multiple forms, delegate calls, ext. Anyway I was wondering is there a way to make global values that can be accessed my any form or class? In otherwords, removing the need to pass in the variables.

Sorry this is rush I have to head off to work but wanted to get this question out. Thanks in advance

Dani AI

Generated

As suggested, a public static "globals" holder will solve the immediate need, and 's example demonstrates that. That approach is fine for true constants or tiny utilities, but it creates hidden dependencies, hurts testability, and can cause concurrency surprises when the values are mutable. The following notes give safer ways to do global-ish data and when to avoid it.

Prefer immutable or read-only globals for configuration (use const or static readonly). If you must share mutable state, wrap it behind a single access point and control access. A common pattern is a thread-safe singleton wrapper rather than many public static fields:

public sealed class AppState
{
    private static readonly Lazy<AppState> _instance = new Lazy<AppState>(() => new AppState());
    public static AppState Instance => _instance.Value;

    private int _screenWidth = 1024;
    public int ScreenWidth
    {
        get => _screenWidth;
        set => _screenWidth = value;
    }
}

Architectural alternatives are better for larger apps: create a single configuration/state object at startup and pass it into forms/services (constructor injection) or use a DI container. For persisted settings, use Properties.Settings.Default or app.config. For cross-form notifications prefer events/delegates or an event-aggregator rather than polling global state.

Practical cautions: avoid public mutable fields (use properties), consider locking or atomic operations for concurrent writes, remember statics live for the AppDomain lifetime, and factor globals out when writing unit tests. If you're prototyping and short on time (as mentioned), a static holder gets you going — but mark it as a refactor target so the codebase stays maintainable.

Recommended Answers

All 4 Replies

You can make a public globals class with public static fields representing the "global" variables. Not exactly a good design, but it works.

dang, can I get an example, do you mean like declaring the variables in a namespace? (Like you would delegates)

namespace MyGlobals {
    public static sealed class Global {
        public static int ScreenWidth = 1024;
    }
}

// somewhere else in your code
    int width = Global.ScreenWidth;

Cool I'll have to try that, that looks like what I wanted

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.