Is it possible to declare global constants? That is, constants that are available in all classes? When I try to declare a constant outside of a class, as I do with an enum, I get a parsing error.
I've been using enums this way for a while, but enums are restricted to integers, and I'd like to use easy-to-use words instead of float values.
Example; I'd like the following to be available in any class:
const float fast = 1.5f;
const float normal = 1f;
const float slow = .75f;
I know i can work around this by creating an enum (Speed) for the speed names, then creating a static method SpeedNum()
that reads enum Speed
and return
s an associated value, but it requires so much extra writing each time and I was hoping for something more elegant:
Ex:
public double function SpeedNum(Speed speed)
{
switch (speed)
{
case speed.fast: return 1.5;
case speed.normal: return 1f;
case speed.slow: return .75f;
}
}
Global Constants. A global constant is a literal value to which you assign a name. Like a global variable, you can access the value of the global constant from any script or 4GL procedure in the application. You set the value for the global constant when you declare it.
Global constants do not become properties of the window object, unlike var variables. An initializer for a constant is required. You must specify its value in the same declaration. (This makes sense, given that it can't be changed later.)
No, these concepts don't play each other. The term global variable is an informal notion, that refers to variables with external linkage. By definition, the automatic variables have no linkage, hence it does not make sense to have variable, that is both automatic and global.
The primary reason why global variables are considered bad practice is because they can be modified in one part of a system and used in another part, with no direct link between those two pieces of code.
Create a static class e.g. called Constants
containing the constants and access them using Constants.MyConstant
.
public static class Constants
{
public const string MyConstant = "Hello world";
public const int TheAnswer = 42;
}
class Foo
{
// ...
private string DoStuff()
{
return Constants.MyConstant;
}
}
To answer your implied question: You cannot declare constants outside of a class.
If you're targeting C# version 6 or higher, and you don't want to use the traditional "static_class_name.Thing", you may use using static, introduced in C# 6.
// File 1
public static class Globals
{
public const string bobsName = "bob!";
}
// File 2
using System;
using static Globals;
class BobFinder
{
void Run() => Console.WriteLine(bobsName);
}
Syntactical sugar. But I find it nifty.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With