Home >Backend Development >C++ >How Can I Achieve Global Variable Functionality in C#?

How Can I Achieve Global Variable Functionality in C#?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2025-01-12 09:20:42297browse

How Can I Achieve Global Variable Functionality in C#?

Using global variables in C#

C# does not support traditional global variables (accessible without any instance reference). However, there are some alternatives to achieve the functionality of global variables.

Use static classes

The most straightforward way is to use static classes. Static classes are not instantiated and can contain static members (variables, properties, and methods) and non-static members. Static members are shared among all instances of a class and can be accessed without creating any instance:

<code class="language-c#">public static class 全局变量
{
    public const Int32 BUFFER_SIZE = 512; // 不可修改
    public static String FILE_NAME = "Output.txt"; // 可修改
    public static readonly String CODE_PREFIX = "US-"; // 不可修改
}</code>

To access a defined value anywhere in code within the same namespace:

<code class="language-c#">String code = 全局变量.CODE_PREFIX + value.ToString();</code>

Handling different namespaces

To access global variables from different namespaces, there are two ways:

  • Declare a global variable class without a namespace: Remove the namespace declaration from the global variable class so that it becomes part of the global application namespace and can be accessed from any namespace.
  • Usage Directives: Include appropriate namespace usage directives in code that accesses variables from another namespace.

The above is the detailed content of How Can I Achieve Global Variable Functionality in C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn