Namespace constant in C#
Asked Answered
L

5

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

Lockwood answered 12/5, 2010 at 11:30 Comment(1)
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".Patrickpatrilateral
S
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);
    }
}
Spadiceous answered 12/5, 2010 at 11:35 Comment(2)
+1 as this is the Microsoft recommended method msdn.microsoft.com/en-us/library/bb397677.aspxBranchiopod
As an aside, another way to implement this is with your web.config or app.config (depending on which one you have). https://mcmap.net/q/270575/-can-we-declare-variables-in-the-39-app-config-39-fileFormal
D
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)

Drainpipe answered 12/5, 2010 at 11:32 Comment(0)
U
8

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);
    }
}
Unwilled answered 30/3, 2019 at 0:9 Comment(1)
thanks, also works with using static MyNameSpace.MyEnum;Liebknecht
C
3

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

Cribbage answered 12/5, 2010 at 11:34 Comment(0)
M
1

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);
    }
}
Mcalpine answered 9/5, 2022 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.