When trying to compile my class I get an error:
The constant
'NamespaceName.ClassName.CONST_NAME'
cannot be marked static.
at the line:
public static const string CONST_NAME = "blah";
I could do this all of the time in Java. What am I doing wrong? And why doesn't it let me do this?
So combining static and const, we can say that when a variable is initialized using static const, it will retain its value till the execution of the program and also, it will not accept any change in its value.
From the C# language specification (PDF page 287 - or 300th page of the PDF): Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier.
public const string ConnectionString = "YourConnectionString"; The value in a const variable is what's called a "compile-time" value, and is immutable (which means it does not change over the life of the program). Only primitive or "built-in" C# types (e.g. int, string, double) are allowed to be declared const .
In C#, static means something which cannot be instantiated. You cannot create an object of a static class and cannot access static members using an object. C# classes, variables, methods, properties, operators, events, and constructors can be defined as static using the static modifier keyword.
So if the const value in the referenced assembly changes, your assembly will still have the originally compiled-in value. If this behavior is not acceptable, then you should consider making the field a public static readonly field. public class Foo { public const int HATS = 42; public static readonly int GLOVES = 33; }
You can't have static const. Try readonly instead of const or simply drop the "static" since "const" is implied static anyway. Constants cannot be replaced in the code during compilation, not runtime, so there's no requirement for static vs instance definitions.
2 const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not. Share Improve this answer Follow
The constant cannot be marked static 52 Static Constants in C# 27 What is the difference between Const and Static in C#? Related 591 Can I add extension methods to an existing static class?
A const
object is always static
.
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