Constants
As you can guess from the name, constants-represented by the const keyword-are fields that remain constant for the life of the application. There are only two rules to keep in mind when defining something as a const. First, a constant is a member whose value is set at compile time, either by the programmer or defaulted by the compiler. Second, a constant member's value must be written as a literal.-
To define a field as a constant, specify the const keyword before the member being defined, as follows: -
using System; class MagicNumbers { public const double pi = 3.1415; public const int answerToAllLifesQuestions = 42; } class ConstApp { public static void Main() { Console.WriteLine("pi = {0}, everything else = {1}", MagicNumbers.pi, MagicNumbers.answerToAllLifesQuestions); } }
Notice one key point about this code. There's no need for the client to instantiate the MagicNumbers class because by default const members are static. To get a better picture of this, take a look at the following MSIL that was generated for these two members: -
answerToAllLifesQuestions : public static literal int32 = int32(0x0000002A) pi : public static literal float64 = float64(3.1415000000000002)