I am working on a new project and I have noticed some code that I am not sure is true. The names and values I am using to demonstrate the question are fake.
public class MyConsts //Should it be static?
{
public const string MyConst1 = "a";
public const string MyConst2 = "b";
public const string MyConst3 = "c";
public const string MyConst4 = "d";
....
}
For my logic this class (that contains only consts values) should be static, so no option to initialize it, which has no sense, am I correct?
EDIT: I was writing the code blind so I have confused the order of string and const - and because it wasn't the target of my question I've fixed this.
To define a string constant in C++, you have to include the string header library, then create the string constant using this class and the const keyword.
Constant. The const keyword converts nothing more but a constant. The specialty of these variables is that they need to have a value at compile time and, by default, they are static. This default value means that a single copy of the variable is created and shared among all objects.
A string constant is an arbitrary sequence of characters that are enclosed in single quotation marks (' '). For example, 'This is a string'. You can embed single quotation marks in strings by typing two adjacent single quotation marks.
Constant. Constant fields or local variables must be assigned a value at the time of declaration and after that, they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
Yes, it makes sense for it to be static. That signifies your intention, prevents clients from even declaring a variable of that type, etc.
You'll need to move the const
modifier before the type part though:
public const string MyConst1 = "a";
...
If the values could ever change, consider using public static readonly
fields instead of const
though - otherwise the value will be baked into any code which refers to the constants, which means you need to rebuild any client code if the values change.
(Another option is to make the constants internal
instead of public
.)
Yes the class should be static
. But related, should those values actually be const
?
Anything declared const
will be compiled into any referencing assemblies, so if this is a class library, say, and you put out a new version with changes to those const values, they won't be picked up by the assemblies that reference them.
In that particular case public static readonly string
makes sense.
However, if those are only visible within a single particular assembly (for instance a console application or WinForms app), then you should declare that class internal
and the const
s are fine as-is.
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