HomeSearch

C# const Example

Use the const keyword to indicate a constant value. Const values cannot be assigned during runtime.
Const is a keyword that indicates a constant. It describes an entity that cannot be changed at program runtime. Instead, the entity must be fully resolved at compile-time.Keywords
We cannot reassign a constant. With constants, we lose the ability to modify variables at runtime but we gain performance and compile-time validation.Optimization
First example. With const we pull constant values (such as strings or ints) into a part of the program that is easier for us to manage and edit. This improves program organization.

Tip: When you compile const values, the values are inserted into the parts of the program that use them.

And: This eliminates any variable lookup overhead. Const declarations at the class level are retained in the assembly metadata.

Class
C# program that uses const using System; class Program { const string _html = ".html"; static void Main() { // This causes a compile-time error: // _html = ""; Console.WriteLine(_html); // Access constant Console.WriteLine(Program._html); // Access constant const string txt = ".txt"; // This causes a compile-time error also: // txt = ""; Console.WriteLine(txt); } } Output .html .html .txt
Some notes. The program contains two assignment statements that are commented out. They reference const identifiers. They would result in a compile-time error if they were uncommented.

Note: Compile-time errors are separate from exceptions and are raised before you can ever execute the program.

Assignment: You cannot assign const identifiers after compile-time. But you can access them as much as you want.

Const, static. The program above accesses the _html constant string in two ways. You can read a constant in the same way as a static variable.Static

Public: You can also describe the constant with the public accessibility modifier to use it throughout your program.

Errors, notes. When refactoring, we may run into some errors related to constants. A compile-time error will occur if we try to assign constants at runtime after they are already assigned.

Tip: To fix this error, either modify the constant to make it a variable, or remove the assignment.

Compile-Time Error
Left-hand side error. This is what happens when we try to mutate a constant value. We get a C# compile-time error. This program won't go far in life.
C# program that causes left-hand side error class Program { static void Main() { const int value = 10; value = 20; } } Output Error CS0131 The left-hand side of an assignment must be a variable, property or indexer
Constant error. All parts of a constant expression must themselves be constant. So we cannot buildup a const from variables. No variables are allowed.
C# program that causes constant error class Program { static void Main() { int size = 5; const int value = 10 + size; } } Output Error CS0133 The expression being assigned to 'value' must be constant
Advantages. Constants promote the integrity of your programs by telling the compiler not to allow you to change the values during runtime. This should result in fewer accidental bugs.

Quote: Magic numbers are literal numbers, such as 100 or 47524, that appear in the middle of a program without explanation. If you program in a language that supports named constants, use them instead (Code Complete).

Performance notes. Const may improve performance over variables in many cases, particularly when using types like int. It eliminates accesses to memory that occur with fields and locals.Readonly
A summary. Const is a reserved word. It specifies that a value is invariant and must not be modified after compile-time. Const values, like const strings, simplify and optimize programs.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls