"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

 About This Book

 Introduction of C# (C Sharp)

 Data Type and Variables

 Logical Expressions and Conditional Statements

 Arrays and Loop Statements

 Data Type Features

 Floating-Point Data Types

 Passing Parameters to Methods

 Execution Environment Class

 Visual C# 2010 Express Edition

Class Features

"const" and "readonly" Variables

 Method Overloading

 Properties

 Operators

 C# Compiler and Intermediate Language

 Compiling C# Source Code Files

 MSBuild - Microsoft Build Engine

 Memory Usages of Processes

 Multithreading in C#

 Async Feature from C# 5

 System.IO.FileInfo Class

 System.Diagnostics.FileVersionInfo Class

 WPF - Windows Presentation Foundation

 Partial Classes and Partial Methods

 Archived Tutorials

 References

 Full Version in PDF/ePUB