'Namespace constant in C#
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
Solution 1:[1]
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)
Solution 2:[2]
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);
}
}
Solution 3:[3]
No, there is not. Put it in a static class or enum.
Solution 4:[4]
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);
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | KenIchi |
| Solution 2 | geisterfurz007 |
| Solution 3 | Svante Svenson |
| Solution 4 | Halil Ibrahim Özcan |
