C Sharp

Constants vs. Read-Only Fields

There will certainly be times when you have fields that you do not want altered during the execution of the application-for example, data files your application depends on, the value of pi for a math class, or any value that you use in your application that you know will never change. To address these situations, C# allows for the definition of two closely related member types: constants and read-only fields.

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)

by BrainBellupdated
Advertisement: