C# Tutorials - Herong's Tutorial Examples - v3.32, by Herong Yang
"const" and "readonly" Variables
This section describes differences between 'const' and 'readonly' variables used in classes.
C# has two key words to prevent values of variables to be changed unwantedly: const and readonly. Here is a comparison of the two:
"const"
"readonly"
The following sample program shows some interesting features:
// Constants.cs // Copyright (c) 2008 HerongYang.com. All Rights Reserved. class Constants { public const long minimum = 1; // const is also static public const long maximum = 100; public static readonly long average = 50; public static readonly string author = "Herong Yang"; public static readonly int[] seeds = new int[] {3, 7, 11}; public static void Main() { // minimum = 0; // assignment not allowed // maximum = 99; // average = 49; // assignment not allowed // author = "Someone Else"; // assignment not allowed // seeds = new int[] {13, 17, 19}; // can not change reference seeds[0] = 5; // but, we can change value it is referring System.Console.WriteLine("Constants.minimum = {0}.", Constants.minimum); System.Console.WriteLine("Constants.maximum = {0}.", Constants.maximum); System.Console.WriteLine("Constants.average = {0}.", Constants.average); System.Console.WriteLine("Constants.author = {0}.", Constants.author); System.Console.WriteLine("Constants.seeds[0] = {0}.", Constants.seeds[0]); } }
Output:
Constants.minimum = 1. Constants.maximum = 100. Constants.average = 50. Constants.author = Herong Yang. Constants.seeds[0] = 5.
Table of Contents
Logical Expressions and Conditional Statements
Visual C# 2010 Express Edition
►"const" and "readonly" Variables
C# Compiler and Intermediate Language
Compiling C# Source Code Files
MSBuild - Microsoft Build Engine
System.Diagnostics.FileVersionInfo Class
WPF - Windows Presentation Foundation