How can I get the number of enums as a constant? - c#

From Total number of items defined in an enum, I see I can get the number of enums by using:
Enum.GetNames(typeof(Item.Type)).Length;
Works great!
But, I need this number as a constant number, so that I can use it in Unity's [Range(int, int)] feature.
private const int constEnumCount = Enum.GetNames(typeof(Item.Type)).Length;
The above does not work, because the enum count is not a constant number, so I cannot assign it to a constant variable.
How can I get the number of enums as a constant?

It's not possible to get the number of enums as a const. Enum.GetNames uses reflection to get these things, and that's inherently a runtime operation. Therefore, it can't be known at compile time, which is a requirement for being const.

Unfortunately, this is not possible to do in any meaningful way due to technical limitations:
[Range(int,int)] is an attribute, and all information provided to an attribute has to be a const
The only truly bulletproof way to get the number of values in an enum is to use Enum.GetValues(typeof(MyEnum)).Length or the Enum.GetNames(typeof(MyEnum)).Length, both of which are run time reflection.
However, there are hacks that can sort of work. For example, the value of an enum can be cast to an integer. As long as nobody is explicitly defining values for your enums you can use the last element in your enum kind of like this:
[Range(0,(int)MyEnum.LastValue)]
public void BlahBlahBlah() {}
However, know that as soon as someone adds a new entry to the enum after the one you are using or reorders the elements in the enum, your code will break unpredictably and not behave like you want.
It's sad, but the C# compiler is not smart enough to do simple math in the compiler like Java, C, and C++ compilers. So even the example I gave would only really work if the LastValue wasn't ever used for anything except to mark the last element in the enum. It lowers the complexity of the C# compiler, which also greatly improves the compilation speed for your application. As such, there are some trade-offs that the C# and CLR team took to improve your experience in other places.

Assuming that you need a const because you are trying to specify the values for an Attribute (this one?) then you are out of luck.
Your options are:
Hardcode the count in the attribute declaration or as a const itself and be careful to keep the count in sync with the enum definition
Use PostSharp or some other aspect oriented framework to insert the attribute for you. Have never done this myself but it looks possible (How to inject an attribute using a PostSharp attribute?)
You could probably also finagle some way to so this with T4 templates but that would get excessively kludgy.
Were it me, unless you are talking but hundreds of different set of enumerations, I'd hardcode the length and maybe add an Assert where I needed it.
// WARNING - if you add members update impacted Range attributes
public enum MyEnum
{
foo,
bar,
baz
}
[Range(0, 3)]
class Test
{
public Test()
{
int enumCount = Enum.GetNames(typeof(MyEnum)).Length;
int rangeMax = GetType().GetCustomAttributes(typeof(Range), false).OfType<Range>().First().Max;
Debug.Assert(enumCount == rangeMax);
}
static void Main(string[] args)
{
var test = new Test();
}
}

Super late to the game here but I've always used a nifty hack when using enum defaults (i.e. no custom values).
public enum MyEnum {
foo,
bar,
baz,
count
}
Since enums default to starting with 0, ensuring the last entry is named simply 'count' ensures that the value of count is in fact the number of values in the enum itself.
private const int constEnumCount = (int)MyEnum.count;
Cheers!

You cannot assign/create a const at runtime. That is what you are trying to do. A const has to be fully evaluated at compile time, not runtime.
I am not sure about Unity (and why it requires a const), but I would look for using readonly
private readonly int constEnumCount = Enum.GetNames(typeof(Item.Type)).Length;

In C#, a const is defined as constant, i.e. the value (not the calculation which produced it!) is directly embedded in the compiled assembly.
To stop you from doing something problematic, the compiler does not allow you to assign the result of a calculation to a const. To understand why, imagine it were possible:
A.dll
public enum Foo { A, B }
B.dll
public const NumberOfFoos = Enum.GetNames(typeof(Foo)).Length;
// Compiles to:
B.dll
public const NumberOfFoos = 2;
Now you change A.dll:
A.dll
public enum Foo { A, B, C, D }
B.dll
public const NumberOfFoos = 2; // Oh no!
So you would need to recompile B.dll to get the correct value.
It gets worse: Imagine you had an assembly C.dll, which uses B.NumberOfFoos. The value 2 would be directly embedded in C.dll, so it also would need to be recompiled, after B.dll, in order to get the correct value. Therefore (pit of success), C# does not allow you to do that assignment to a const.

Related

Declaring constants with the nameof() the constant as the value

Scenario
I have a class for declaring string constants used around a program:
public static class StringConstants
{
public const string ConstantA = "ConstantA";
public const string ConstantB = "ConstantB";
// ...
}
Essentially, it doesn't matter what the actual value of the constant is, as it used when assigning and consuming. It is just for checking against.
The constant names will be fairly self-explanatory, but I want to try and avoid using the same string values more than once.
What I would like to do
I know that nameof() is evaluated at compile-time, so it is entirely possible to assign the const string's value to the nameof() a member.
In order to save writing these magic strings out, I have thought about using the nameof() the constant itself.
Like so:
public static class StringConstants
{
public const string ConstantA = nameof(ConstantA);
public const string ConstantB = nameof(ConstantB);
// ...
}
Question...
I guess there is no real benefit of using the nameof(), other than for refactoring?
Are there any implications to using nameof() when assigning constants?
Should I stick to just using a hard-coded string?
Whilst I think the use of nameof is clever, I can think of a few scenarios where it might cause you a problem (not all of these might apply to you):
1/ There are some string values for which you can't have the name and value the same. Any string value starting with a number for example can't be used as a name of a constant. So you will have exceptions where you can't use nameof.
2/ Depending how these values are used (for example if they are names of values stored in a database, in an xml file, etc), then you aren't at liberty to change the values - which is fine until you come to refactor. If you want to rename a constant to make it more readable (or correct the previous developer's spelling mistake) then you can't change it if you are using nameof.
3/ For other developers who have to maintain your code, consider which is more readable:
public const string ConstantA = nameof(ContantA);
or
public const string ConstantA = "ConstantA";
Personally I think it is the latter. In my opinion if you go the nameof route then that might give other developers cause to stop and wonder why you did it that way. It is also implying that it is the name of the constant that is important, whereas if your usage scenario is anything like mine then it is the value that is important and the name is for convenience.
If you accept that there are times when you couldn't use nameof, then is there any real benefit in using it at all? I don't see any disadvantages aside from the above. Personally I would advocate sticking to traditional hard coded string constants.
That all said, if your objective is to simply to ensure that you are not using the same string value more than once, then (because this will give you a compiler error if two names are the same) this would be a very effective solution.
I think nameof() has 2 advantages over a literal strings:
1.) When the name changes, you will get compiler errors unless you change all occurences. So this is less error-prone.
2.) When quickly trying to understand code you didn't write yourself, you can clearly distinguish which context the name comes from. Example:
ViewModel1.PropertyChanged += OnPropertyChanged; // add the event handler in line 50
...
void OnPropertyChanged(object sender, string propertyName) // event handler in line 600
{
if (propertyName == nameof(ViewModel1.Color))
{
// no need to scroll up to line 50 in order to see
// that we're dealing with ViewModel1's properties
...
}
}
Using the nameof() operator with public constant strings is risky. As its name suggests, the value of a public constant should really be constant/permanent. If you have public constant declared with the nameof() and if you rename it later then you may break your client code using the constant. In his book Essential C# 4.0, Mark Michaelis points out: (Emphasis is mine)
public constants should be permanent because changing their value will
not necessarily take effect in the assemblies that use it. If an
assembly references constants from a different assembly, the value of
the constant is compiled directly into the referencing assembly.
Therefore, if the value in the referenced assembly is changed but the
referencing assembly is not recompiled, then the referencing assembly
will still use the original value, not the new value. Values that
could potentially change in the future should be specified as readonly
instead.

Enum.GetName() As Constant property

I have been working in C# for about 8 months so forgive me if this is dumb...
I have an enum that I will need the string value several times in a class. So I want to use Enum.GetName() to set it to a string variable which is no problem. I just do it like so...
private string MyEnumString = Enum.GetName(typeof(MyEnum), MyEnum.Name);
And it works just fine.
But I tried to protect it a little better because this particular Enum is more important that all the others and it would not be good if I accidentally changed the string value somehow so I tried to make it const like this.
private const string MyEnumString = Enum.GetName(typeof(MyEnum), MyEnum.Name);
To my eyes this seems fine as it should all be known at compile time.
But Visual Studio 2013 Throws an error saying the "Cannot resolve symbol GetName". I know it works when it is not marked "const".
So this leads me with two questions about this?
Why does it loose reference to the GetName enum? (After a bit of research I suspect it is something to do with GetName being a method and not a property of the Enum class but the error message just does not make sense to me)
And Finally is there a way to read the Name of MyEnum.Name to a const string other than what I am doing?
Just make it readonly:
private readonly string MyEnumString = Enum.GetName(typeof(MyEnum), MyEnum.Name);
Then it can't be changed afterwards.
You can't assign the result of calling a method to a constant; C# just doesn't allow it - the compiler would have to be calling that method at compile time, possibly before it was even compiled (and not only would it have to generate the IL, it would have to use the JIT compiler to compile that IL).
Enum.GetName(typeof(MyEnum), MyEnum.Name); is calling a method, so you can't assign the result to a constant.
[EDIT] As Jon Skeet says in a comment above, you can use nameof if using C#6 or later (i.e. VS2015 or later):
private const string MyEnumString = nameof(MyEnum.Name);
nameof works because here you are not calling an arbitrary method, but you are instead using a compiler feature to access the name of a type.
You cannot use result of the method as constant, because method evaluation can occur only at runtime. The value of the constant must be known at compile time. In order for compiler to be able to evaluate that constant, it would need to know the semantics of Enum.GetName and execute it at compile time, which is not possible
You can mark it as static readonly instead. That way it will be set once per type where it is declared and it cannot be changed anymore at runtime.
It may not even be known at run-time:
From MSDN:
If multiple enumeration members have the same underlying value, the GetName method guarantees that it will return the name of one of those enumeration members. However, it does not guarantee that it will always return the name of the same enumeration member.
(emphasis added)
void Main()
{
Console.WriteLine (Enum.GetName(typeof(Test),Test.One));
}
public enum Test
{
Zero,
One,
Two,
Uno = 1,
Dos = 2,
}
I consistently get the output Uno for the program above.
The reason is it not known is because enums are compiled to the underlying value. The call above is essentially compiled to Enum.GetName(typeof(Test), 1). GetName looks for a member with that value to find the name. How it does that is apparently an implementation detail that may not product consistent results.
What you can use for a constant in C#6 and later is nameof:
private const string MyEnumString = nameof(MyEnum.Name);

What's the idea behind allowing private constant to be used as default parameters for public methods?

To my surprise, this one compiles and runs:
class Program
{
static void Main()
{
DoSomething();
}
private const int DefaultValue = 2; // <-- Here, private.
public static void DoSomething(int value = DefaultValue)
{
Console.WriteLine(value);
}
}
The method is public whereas the default value "redirects" to a constant private variable.
My question:
What is/was the idea behind this "concept"?
My understanding (until today) was, that something public can only be used if all other "referenced" elements are also public.
Update:
I just ILSpy-decompiled my class to find:
static class Program
{
private static void Main()
{
Program.DoSomething(2);
}
private const int DefaultValue = 2;
public static void DoSomething(int value = 2)
{
Console.WriteLine(value);
}
}
So if the private constant as a default parameter is being done in e.g. a library, the user of the library still sees the default parameter.
What is/was the idea behind this "concept"?
The idea is that as const value is static and never changes - you can use it as default value for method's optional parameters same as you can use normal values. A quote from MSDN :
Each optional parameter has a default value as part of its definition. If no argument is sent for that parameter, the default value is used. A default value must be one of the following types of expressions:
a constant expression;
an expression of the form new ValType(), where ValType is a value
type, such as an enum or a struct;
an expression of the form default(ValType), where ValType is a value
type.
My understanding (until today) was, that something public can only be
used if all other "referenced" elements are also public
Well technically speaking it's correct. But in your scenario both members are accessible as they are defined in the same class however should const in our case be defined outside of class Program it'd be inaccessible inside class Program.
The name DefaultValue is private, but the number 2 is still the number 2.
Because DefaultValue is private, we cannot access Program.DefaultValue from outside of Program. Presumably we wouldn't particularly want to.
And because we've bothered to define DefaultValue at all, it's presumably something that we do care about when we are working on how Program works.
So when we come to define a default value for DoSomething there's presumably some logical reason why the value we want there happens to be the same as the value DefaultValue.
And as such, it's presumably beneficial to be able to use that constant there, for much the same reasons as we would find constants beneficial anywhere.
And since DefaultValue is just a Program-specific way of saying 2, there's no real reason why we can't.
Of course, the metadata would reflect this as 2 rather than the (meaningless to the outside) DefaultValue, but then that would hold if the const was public anyway (the metadata about default values gives only the value, not whether or not it related to any defined constants).
So there's no downside.
So considering that:
There's an advantage to the implementer.
There's no disadvantage to the user, over just a use of a literal 2.
Preventing it would have to introduce a special rule to be an exception to the rule that defined constants can be used anywhere a constant value from a literal can.
Why not?
When you use const, the compiler replaces all the occurrences of the variable with the actual value ,so your code is the same as this:
public static void DoSomething(int value = 2)
Constant variables are replaced at compile-time, so they never really exist in the produced assembly. So code using a constant is really identical to just using the constant value directly. The benefit is just that you can reuse the constant elsewhere and only need to change it in one location.
Now, since constants are always replaced at compile-time, the effect of making them public or private is also quite simple: It just affects what other type can access it at compile-time. So using a private constant for example can be helpful if you just want to keep that constant to the current type, whereas a public constant can be used across the whole application.

Local constant initialised to null reference

I have read that C# allows local constants to be initialised to the null reference, for example:
const string MyString = null;
Is there any point in doing so however? What possible uses would this have?
My guess is because null is a valid value that can be assigned to reference types and nullable values types.
I can't see any reason to forbid this.
There might be some far off edge cases where this can be useful, for example with multi targeting and conditional compilation. IE you want to define a constant for one platform but define it as null for another due to missing functionality.
Ex, of possible usefull usage:
#IF (SILVELIGHT)
public const string DefaultName = null;
#ELSE
public const string DefaultName = "Win7";
#ENDIF
Indeed, you can initialize local const strings and readonly reference types to null, even though it seems to be redundant since their default value is null anyway.
However, the fact remains that null is a compile-time constant suitable enough to initialize strings and reference types. Therefore, the compiler would have to go out of its way in order to consider, identify and reject this special case, even though it's still perfectly valid from a language standpoint.
The merits of doing that would be disputable, and it probably wouldn't be worth the effort in the first place.
It could be used if you want to write code without keywords, if that strikes your fancy:
const string UninitializedSetting = null;
if (mySetting == UninitializedSetting)
{
Error("mySetting string not initialized");
}
Choosing to name a value (rather than using an in-place magic constant), using const, and setting to null are more or less orthogonal issues, although I agree that the venn diagram might have a very small area of overlap for the three :)
A case that I can think of is when you have as much or more throw-away data than you do code, but you want to ensure the values don't accidentally get changed while writing or maintaining your code. This situation is fairly common in unit tests:
[Test]
public void CtorNullUserName()
{
const string expectedUserName = null;
var user = new User(expectedUserName);
Assert.AreEqual(expectedUserName, user.Name, "Expected user name to be unchanged from ctor");
}
You could arguably structure such code in a plethora of ways that didn't involve assigning null to a const, but this is still a valid option.
This might also be useful to help resolve method overloading issues:
public class Something
{
public void DoSomething(int? value) { Console.WriteLine("int?"); }
public void DoSomething(string value) { Console.WriteLine("string"); }
}
// ...
new Something().DoSomething(null); // This is ambiguous, and won't compile
const string value = null;
new Something().DoSomething(value); // Not ambiguous
If you use constants, for example, for configuration of your application then why not? The null value can represent a valid state - e.g. that a logger is not installed. Also note that when you declare a local constant, you can initialize it to a value given by global constant (which may be a more interesting scenario).
EDIT: Another question is, what are good situations for using const anyway? For configuration, you'd probably want a configuration file and other variables usually change (unless they are immutable, but then readonly is a better fit...)
Besides the situations already pointed out, it may have to do with a quirk of the C# language. The C# Specification 3.0, section 8.5.2 states:
The type and constant-expression of a local constant declaration must follow the same rules as those of a constant member declaration (§10.4).
And within 10.4 reads as follows:
As described in §7.18, a constant-expression is an expression that can be fully evaluated at compile-time. Since the only way to create a non-null value of a reference-type other than string is to apply the new operator, and since the new operator is not permitted in a constant-expression, the only possible value for constants of reference-types other than string is null.

'Static readonly' vs. 'const'

I've read around about const and static readonly fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:
Should these kind of constant values always be static readonly for everything that is public? And only use const for internal/protected/private values?
What do you recommend? Should I maybe even not use static readonly fields, but rather use properties maybe?
public static readonly fields are a little unusual; public static properties (with only a get) would be more common (perhaps backed by a private static readonly field).
const values are burned directly into the call-site; this is double edged:
it is useless if the value is fetched at runtime, perhaps from config
if you change the value of a const, you need to rebuild all the clients
but it can be faster, as it avoids a method call...
...which might sometimes have been inlined by the JIT anyway
If the value will never change, then const is fine - Zero etc make reasonable consts ;p Other than that, static properties are more common.
I would use static readonly if the Consumer is in a different assembly. Having the const and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
A few more relevant things to be noted:
const int a
must be initialized.
initialization must be at compile time.
readonly int a
can use a default value, without initializing.
initialization can be done at run time (Edit: within constructor only).
This is just a supplement to the other answers. I will not repeat them (now four years later).
There are situations where a const and a non-const have different semantics. For example:
const int y = 42;
static void Main()
{
short x = 42;
Console.WriteLine(x.Equals(y));
}
prints out True, whereas:
static readonly int y = 42;
static void Main()
{
short x = 42;
Console.WriteLine(x.Equals(y));
}
writes False.
The reason is that the method x.Equals has two overloads, one that takes in a short (System.Int16) and one that takes an object (System.Object). Now the question is whether one or both apply with my y argument.
When y is a compile-time constant (literal), the const case, it becomes important that there does exist an implicit conversion from int to short provided that the int is a constant, and provided that the C# compiler verifies that its value is within the range of a short (which 42 is). See Implicit constant expression conversions in the C# Language Specification. So both overloads have to be considered. The overload Equals(short) is preferred (any short is an object, but not all object are short). So y is converted to short, and that overload is used. Then Equals compares two short of identical value, and that gives true.
When y is not a constant, no implicit conversion from int to short exists. That's because in general an int may be too huge to fit into a short. (An explicit conversion does exist, but I didn't say Equals((short)y), so that's not relevant.) We see that only one overload applies, the Equals(object) one. So y is boxed to object. Then Equals is going to compare a System.Int16 to a System.Int32, and since the run-time types do not even agree, that will yield false.
We conclude that in some (rare) cases, changing a const type member to a static readonly field (or the other way, when that is possible) can change the behavior of the program.
One thing to note is const is restricted to primitive/value types (the exception being strings).
Static Read Only:
The value can be changed through a static constructor at runtime. But not through a member function.
Constant:
By default static. A value cannot be changed from anywhere (constructor, function, runtime, etc. nowhere).
Read Only:
The value can be changed through a constructor at runtime. But not through a member function.
You can have a look at my repository: C# property types.
The readonly keyword is different from the const keyword. A const field can only be initialized at the declaration of the field. A readonly field can be initialized either at the declaration or in a constructor. Therefore, readonly fields can have different values depending on the constructor used. Also, while a const field is a compile-time constant, the readonly field can be used for runtime constants
From this short and clear MSDN reference.
const and readonly are similar, but they are not exactly the same.
A const field is a compile-time constant, meaning that that value can be computed at compile-time. A readonly field enables additional scenarios in which some code must be run during construction of the type. After construction, a readonly field cannot be changed.
For instance, const members can be used to define members like:
struct Test
{
public const double Pi = 3.14;
public const int Zero = 0;
}
Since values like 3.14 and 0 are compile-time constants. However, consider the case where you define a type and want to provide some pre-fab instances of it. E.g., you might want to define a Color class and provide "constants" for common colors like Black, White, etc. It isn't possible to do this with const members, as the right hand sides are not compile-time constants. One could do this with regular static members:
public class Color
{
public static Color Black = new Color(0, 0, 0);
public static Color White = new Color(255, 255, 255);
public static Color Red = new Color(255, 0, 0);
public static Color Green = new Color(0, 255, 0);
public static Color Blue = new Color(0, 0, 255);
private byte red, green, blue;
public Color(byte r, byte g, byte b) => (red, green, blue) = (r, g, b);
}
But then there is nothing to keep a client of Color from mucking with it, perhaps by swapping the Black and White values. Needless to say, this would cause consternation for other clients of the Color class. The "readonly" feature addresses this scenario.
By simply introducing the readonly keyword in the declarations, we preserve the flexible initialization while preventing client code from mucking around.
public class Color
{
public static readonly Color Black = new Color(0, 0, 0);
public static readonly Color White = new Color(255, 255, 255);
public static readonly Color Red = new Color(255, 0, 0);
public static readonly Color Green = new Color(0, 255, 0);
public static readonly Color Blue = new Color(0, 0, 255);
private byte red, green, blue;
public Color(byte r, byte g, byte b) => (red, green, blue) = (r, g, b);
}
It is interesting to note that const members are always static, whereas a readonly member can be either static or not, just like a regular field.
It is possible to use a single keyword for these two purposes, but this leads to either versioning problems or performance problems. Assume for a moment that we used a single keyword for this (const) and a developer wrote:
public class A
{
public static const C = 0;
}
and a different developer wrote code that relied on A:
public class B
{
static void Main() => Console.WriteLine(A.C);
}
Now, can the code that is generated rely on the fact that A.C is a compile-time constant? I.e., can the use of A.C simply be replaced by the value 0? If you say "yes" to this, then that means that the developer of A cannot change the way that A.C is initialized -- this ties the hands of the developer of A without permission.
If you say "no" to this question then an important optimization is missed. Perhaps the author of A is positive that A.C will always be zero. The use of both const and readonly allows the developer of A to specify the intent. This makes for better versioning behavior and also better performance.
My preference is to use const whenever I can, which, as mentioned in previous answers, is limited to literal expressions or something that does not require evaluation.
If I hit up against that limitation, then I fallback to static readonly, with one caveat. I would generally use a public static property with a getter and a backing private static readonly field as Marc mentions here.
Const: Constant variable values have to be defined along with the declaration and after that it won't change.const are implicitly static, so without creating a class instance we can access them. This has a value at compile time.
ReadOnly: We can define read-only variable values while declaring as well as using the constructor at runtime. Read-only variables can't access without a class instance.
Static readonly: We can define static readonly variable values while declaring as well as only through a static constructor, but not with any other constructor. We can also access these variables without creating a class instance (as static variables).
Static readonly will be better choice if we have to consume the variables in different assemblies. Please check the full details in the below blog post:
Const Strings – a very convenient way to shoot yourself in the foot
A static readonly field is advantageous when exposing to
other assemblies a value that might change in a later version.
For instance, suppose assembly X exposes a constant as follows:
public const decimal ProgramVersion = 2.3;
If assembly Y references X and uses this constant, the value 2.3
will be baked into assembly Y when compiled. This means that
if X is later recompiled with the constant set to 2.4, Y will still
use the old value of 2.3 until Y is recompiled. A static
readonly field avoids this problem.
Another way of looking at this is that any value that might
change in the future is not constant by definition, and so should
not be represented as one.
Const: Const is nothing but "constant", a variable of which the value is constant but at compile time. And it's mandatory to assign a value to it. By default a const is static and we cannot change the value of a const variable throughout the entire program.
Static ReadOnly: A Static Readonly type variable's value can be assigned at runtime or assigned at compile time and changed at runtime. But this variable's value can only be changed in the static constructor. And cannot be changed further. It can change only once at runtime
Reference: c-sharpcorner
There is a minor difference between const and static readonly fields in C#.Net
const must be initialized with value at compile time.
const is by default static and needs to be initialized with constant value, which can not be modified later on.
It can not be used with all datatypes. For ex- DateTime. It can not be used with DateTime datatype.
public const DateTime dt = DateTime.Today; //throws compilation error
public const string Name = string.Empty; //throws compilation error
public static readonly string Name = string.Empty; //No error, legal
readonly can be declared as static, but not necessary. No need to initialize at the time of declaration. Its value can be assigned or changed using constructor once. So there is a possibility to change value of readonly field once (does not matter, if it is static or not), which is not possible with const.
const:
value should be given upon declaration
compile time constant
readonly:
value can be given upon declaration or during runtime using constructors.The value may vary depend upon the constructor used.
run time constant
A const (being determined at compile-time) can be used in cases where a readonly static can't, like in switch statements, or attribute constructors. This is because readonly fields are only resolved at run-time, and some code constructs require compile time assurance. A readonly static can be calculated in a constructor, which is often an essential and useful thing. The difference is functional, as should be their usage in my opinion.
In terms of memory allocation, at least with strings (being a reference type), there seems to be no difference in that both are interned and will reference the one interned instance.
Personally, my default is readonly static, as it makes more semantic and logical sense to me, especially since most values are not needed at compile time. And, by the way, public readonly statics are not unusual or uncommon at all as the marked answer states: for instance, System.String.Empty is one.
Another difference between declaring const and static readonly is in memory allocation.
A static field belongs to the type of an object rather than to an instance of that type. As a result, once the class is referenced for the first time, the static field would "live" in the memory for the rest of time, and the same instance of the static field would be referenced by all instances of the type.
On the other hand, a const field "belongs to an instance of the type.
If memory of deallocation is more important for you, prefer to use const. If speed, then use static readonly.
Use const if you can provide a compile-time constant:
private const int Total = 5;
Use static readonly if you need your value evaluated during run-time:
private static readonly int GripKey = Animator.StringToHash("Grip");
This will give a compile error because it is impossible to get the value at compile-time.
private const int GripKey = Animator.StringToHash("Grip");
Constants are like the name implies, fields which don't change and are usually defined statically at compile time in the code.
Read-only variables are fields that can change under specific conditions.
They can be either initialized when you first declare them like a constant, but usually they are initialized during object construction inside the constructor.
They cannot be changed after the initialization takes place, in the conditions mentioned above.
Static read-only sounds like a poor choice to me since, if it's static and it never changes, so just use it public const. If it can change then it's not a constant and then, depending on your needs, you can either use read-only or just a regular variable.
Also, another important distinction is that a constant belongs to the class, while the read-only variable belongs to the instance!
Const
Can be applied only for fields. Value should be in code compile time.
Suited for removing magic "strings","int/double", (primitive types) etc across the code which is known already before compiling the code.
After compiling the value will be placed all over the compiled code wherever constant is used. So if you have a huge string used many places, then watch out before making it const. consider using static read only.
Static read only
Static read only be applied for fields/props and static can be used for methods.
(on side note)When static is applied to methods, the complied code does not pass the 'this' parameter to the method and hence you cannot access the instance data of the object.
Suitable for values which may change after compiling the code. Like values initialized from configuration, during startup of application etc.
After compiling the code, the ref to value is used in IL code and may be slower compared to using const, but compiled code is small
During Refactoring, All const can be safely converted to Static read only, but not vise versa as we have seen above when converted code may break as some static readonly variable could be initialized in constructors.
There is one important question, that is not mentioned anywhere in the above answers, and should drive you to prefer "const" especially for basic types like "int", "string" etc.
Constants can be used as Attribute parameters, static readonly field not!
Azure functions HttpTrigger, not using HttpMethods class in attribute
If only microsoft used constants for Http's GET, POST, DELETE etc.
It would be possible to write
[HttpTrigger(AuthorizationLeve.Anonymous, HttpMethods.Get)] // COMPILE ERROR: static readonly,
But instead I have to resort to
[HttpTrigger(AuthorizationLeve.Anonymous, "GET")] // STRING
Or use my own constant:
public class HttpConstants
{
public const string Get = "GET";
}
[HttpTrigger(AuthorizationLeve.Anonymous, HttpConstants.Get)] // Compile FINE!
One additional difference that I don't believe is mentioned above:
const and static readonly values don't get CodeLens applied to them in the Visual Studio IDE.
static get only properties DO get CodeLens applied to them.
I consider the addition of CodeLens to be quite valuable.
Note: Currently using Visual Studio 2022.
Const, readonly, static readonly - keywords that perform a similar action but have an important difference:
• Const - is a variable whose value is constant and is assigned at compile time. You must assign a value to it. The default constants are static, and we cannot change the value of the const variable throughout the program.
• Readonly - means a value that we can change at run time, or we can assign it at run time, but only through a non-static constructor.
• Static readonly - values ​​can be assigned at run time or assigned at compile time and changed at run time. But the value of this variable can be changed only in the static constructor. And cannot be changed further. It can only be changed once during execution.
Examples you can find here - https://www.c-sharpcorner.com/UploadFile/c210df/difference-between-const-readonly-and-static-readonly-in-C-Sharp/

Categories