Start learning free

LESSON 13 OF 347 · VARIABLES

Constants in C#: The const Keyword

Lesson Read the full explanation

There is a special type of variable in C#, which is called a constant.

A constant is a variable that we do not want to change the value of during the whole program.


Creation:

You create a constant variable just like you create a normal one, but adding the keyword const before the variable's data type:

const string ourName = "AlgoCademy";

Console.WriteLine(ourName); // Output: AlgoCademy

Reassignment not allowed:

However, a const variable cannot be reassigned because it is constant. If you try to reassign a const variable, you'll get an error.

For example, this code:

const string ourName = "AlgoCademy";

ourName = "Andy"; // Here is the problem

would produce an error because ourName is a constant.


Usage:

It seems like constants are just variables with some limitations. So, why use them when we can do the same things (and more) with normal variables?

The power of constants lies in their limitation! Constants were invented to provide some level of guarantee that the code can't change the underlying value.

This is not of much importance for a smaller project, but matters on a larger project with multiple components written by multiple authors.

Picture this: You are the first developer to have ever worked at a new startup. When you have written the core code, you created some important variables that describe your company:

const string companyName = "Apple";
const string foundingDate = "April 1st, 1976";
const string founderName = "Steve Jobs";

Ten years later, your company blew up and you have hundreds of Software Engineers managing millions of lines of code.

I bet you wouldn't love it if a Junior Developer was able to do this successfully:

companyName = "Microsoft";
founderName = "Bill Gates";

But you are smart! You made those variables constants ten years ago and have nothing to worry about now. As for the Junior, they'll just get an error and probably a slap on the wrist by their manager.


Assignment
Follow the Coding Tutorial and let's work with constants!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 1
    Ctrl + Enter to check

    C# · VARIABLES

    Constants in C#, explained

    What a constant is

    A constant is a variable whose value can never change. You create one by putting the keyword const before the type:

    const string ourName = "AlgoCademy";
    
    Console.WriteLine(ourName);   // AlgoCademy
    

    Reading a constant works exactly like reading any other variable. The difference is that the compiler refuses every attempt to give it a new value.

    Reassignment is an error

    const double pi = 3.14;
    
    pi = 5;   // error CS0131
    

    C# reports The left-hand side of an assignment must be a variable, property or indexer, which is its way of saying that a constant is not a variable you can assign to. The program does not compile, so nothing runs.

    Why use constants

    If a constant is just a variable with fewer abilities, why bother? Because the limit is the point. A constant is a guarantee. In a small program you can see every line and remember what you changed. In a large one with many authors, nobody can. Marking a value that must not change as const means the compiler stops anyone from changing it by accident, rather than leaving you to discover it from strange behaviour later. A good candidate is any fixed value that other code relies on: a mathematical constant, a limit, the number of days in a week.

    The lesson's pi is only an illustration with a rough value. In real programs, Math.PI already provides a more precise one.

    A const also helps readers. Seeing const tells them the value is fixed, without scanning the code for assignments.

    The rules for const in C#

    • It needs a value at declaration. const int n; is an error, since there would be no way to give it one later.
    • The value must be known when the program is compiled. A literal works, and so does an expression built from literals and other constants. A value that is only known at run time does not:
    const int days = 7;
    const int weeks = 4;
    const int total = days * weeks;      // fine: 28, computed at compile time
    
    const int n = int.Parse("3");        // error CS0133: must be constant
    
    • Only some types can be const. Numbers, bool, char and string work, which covers most uses. A string constant may even be built by joining other constants, as in const string greeting = "Hello, " + ourName;.
    • Naming. The lesson uses camelCase for constants such as ourName. Many C# programmers use PascalCase for constants declared as class members, so you may see that style elsewhere. Following the surrounding code matters more than the choice.

    Because the value is fixed at compile time, the compiler can place it directly where it is used. That is why it can't depend on anything computed while the program runs.

    The exercise, step by step

    The starter program tries to change a constant:

    const double pi = 3.14;
    
    pi = 5;
    
    Console.WriteLine(pi);
    
    1. Find the line that breaks the rule. pi = 5; assigns to a const, which the compiler rejects.
    2. Delete that line. Leave the declaration and the Console.WriteLine as they are. The task is not to remove const from pi, since the value is meant to stay fixed.

    The solution has only the declaration and the print, with blank lines where the assignment was:

    const double pi = 3.14;
    
    
    
    Console.WriteLine(pi);
    

    It prints 3.14.

    Common mistakes

    • Removing const to make the error go away. It compiles, but you have thrown away the protection. Fix the code that tries to change the value instead.
    • Using a run-time value. const can't be initialized from user input, a method call or the current time.
    • Declaring without a value. A constant must be initialized in the same statement.

    Key takeaways

    • const before a type creates a variable that can't be reassigned.
    • The compiler rejects any assignment to it, so mistakes surface before the program runs.
    • A constant must be initialized immediately with a value known at compile time.
    • Use constants for values that should stay fixed everywhere in the program.
    Keep going with C#About 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free