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:
Syntax
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
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);
}
}
Login to try C/C++/Java/PHP code in the editor
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
- Trying to assign to a
constafter declaring it, which is a compile error. - Declaring a
constwithout a value, or with a value that is not known at compile time. - Using
constfor a value that must be computed at runtime, whenreadonlyis the right choice.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: