← Back to C# Course | Chapter 2: Variables & Types | Lesson 6 of 7

const Fields

A const is a value written in permanent marker: you set it once and it can never change. It is perfect for facts like the number of days in a week.

In this page:

  1. const Fields
Syntax
csharp
const type ConstantName = value;   // must be known at compile time

const Fields

A const field is a compile-time constant — its value must be known at compile time and can never change afterward.

Unlike readonly, const values are substituted directly into the compiled code wherever they're used. const is ideal for values like mathematical constants or fixed configuration limits.

Warning: A const cannot be assigned the result of a method call, since its value must be resolvable at compile time.

Example: const Fields

markup
using System;

class Program
{
    const double Pi = 3.14159;
    const int MaxRetries = 3;

    static void Main(string[] args)
    {
        Console.WriteLine(Pi);
        Console.WriteLine(MaxRetries);
        Console.WriteLine(Pi * 2 * 5);
    }
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Trying to assign to a const after declaring it, which is a compile error.
  2. Declaring a const without a value, or with a value that is not known at compile time.
  3. Using const for a value that must be computed at runtime, when readonly is the right choice.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.