Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The constant cannot be marked static

Tags:

c#

I am trying to declare a PI constant like this:

public static const double PI = Math.PI;

but why am I getting this error?

The constant 'Calendar.NewCalendar.PI' cannot be marked static
like image 930
Chin Avatar asked Oct 31 '12 02:10

Chin


People also ask

Why const cannot be static?

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.

Can a const be static?

“static const” is basically a combination of static(a storage specifier) and const(a type qualifier). The static determines the lifetime and visibility/accessibility of the variable.

Is a const always static?

A const object is always static . const makes the variable constant and cannot be changed.

Is const implicitly static?

If you need a field to be a property of a type, and not a property of an instance of that type, use static . A const value is also implicitly static .


2 Answers

const implies static (you don't need an instance to reference the const value).

I want to also add this important point: When you link against (reference) an assembly with a public const, that value is copied into your assembly. 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.

Lib.dll, provided as binary:

public class Foo {
    public const int HATS = 42;
    public static readonly int GLOVES = 33;
}

App.exe, references Lib.dll:

Foo.HATS    // This will always be 42 even if the value in Lib.dll changes,
            // unless App.exe is recompiled.

Foo.GLOVES  // This will always be the same as Foo.GLOVES in Lib.dll

From MSDN:

Don’t create a constant to represent information that you expect to change at any time. For example, don’t use a constant field to store the price of a service, a product version number, or the brand name of a company. These values can change over time, and because compilers propagate constants, other code compiled with your libraries will have to be recompiled to see the changes.

From DotNetPerls:

DLLs. When you use a const field or declaration, the C# compiler actually embeds the const variable's value directly in the IL code. Therefore, it essentially erases the const as a separate entity.

Caution: If programs that depend on a const are not recompiled after the const value changes, they may break [because they'll continue to use the previous value].

like image 91
Jonathon Reinhart Avatar answered Oct 22 '22 18:10

Jonathon Reinhart


A constant is static by definition.

like image 15
juergen d Avatar answered Oct 22 '22 16:10

juergen d