75

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

Paul Michaels
  • 16,185
  • 43
  • 146
  • 269
  • 16
    Note that "constant variable" is an oxymoron. Variables vary, that's why they're called "variables". Constants remain constant, that's why they're called constants. Variables are storage *locations*, constants are *values*. They are completely different; there can be no such thing as a "constant variable". – Eric Lippert May 12 '10 at 14:14

5 Answers5

117

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);
    }
}
alinsoar
  • 15,386
  • 4
  • 57
  • 74
RvdK
  • 19,580
  • 4
  • 64
  • 107
  • 19
    +1 as this is the Microsoft recommended method http://msdn.microsoft.com/en-us/library/bb397677.aspx – Bryan May 12 '10 at 11:41
  • 1
    As an aside, another way to implement this is with your web.config or app.config (depending on which one you have). https://stackoverflow.com/a/4256864/105539 – Volomike Oct 17 '17 at 00:05
14

This is not possible

From MSDN:

The const keyword is used to modify a declaration of a field or local variable.

Since you can only have a field or local variable within a class, this means you cannot have a global const. (i.e namespace const)

KenIchi
  • 1,129
  • 10
  • 22
Oded
  • 489,969
  • 99
  • 883
  • 1,009
6

You can use the constants in your other classes if you add the "Using Static" too:

using static MyNameSpace.MyGlobals;

namespace MyNameSpace {
    public static class MyGlobals{
        public const bool SAVE_LOGSPACE = true;
        public static readonly DateTime BACKTEST_START_DATE = new DateTime(2019,03,01);
    }
}
geisterfurz007
  • 5,292
  • 5
  • 33
  • 54
MrCalico
  • 301
  • 3
  • 8
3

No, there is not. Put it in a static class or enum.

Svante Svenson
  • 12,315
  • 4
  • 41
  • 45
0

I would define a public static class with constants:

namespace Constants
{
    public static class Const
    {
        public const int ConstInt = 420;
    }
}

Inside my Program.cs, i would add the following using:

using static Constants.Const;
using static System.Console;

Now you can freely use the defined constants (which are static by default) and static Console-Methods, e. g.

class Program
{
    static void Main(string[] args)
    {
        WriteLine(ConstInt);
    }
}