Namespace constant in C#

Paul Michaels picture Paul Michaels · May 12, 2010 · Viewed 55.3k times · Source

Is there any way to define a constant for an entire namespace, rather than just within a class? For example:

namespace MyNamespace
{    
    public const string MY_CONST = "Test";

    static class Program
    {
    }
}

Gives a compile error as follows:

Expected class, delegate, enum, interface, or struct

Answer

RvdK picture RvdK · May 12, 2010

I believe it's not possible. But you can create a Class with only constants.

public static class GlobalVar
{
    public const string MY_CONST = "Test";
}

and then use it like

class Program
{
    static void Main()
    {
        Console.WriteLine(GlobalVar.MY_CONST);
    }
}