Friday, April 30, 2021

C# const keyword Examples

The const keyword is used to create a constant field or constant local and cannot be reinitialized throughout the program. The const field or const local must be declared and initialized in one go. It is just a single statement which define constant. For example, public const double PI = 3.1415;

Example1 : Program with Error

using System;

namespace Console_const_keyword
{
    class Program
    {
        const double PI;// const field must be initialized when declared
        Pl = 3.1415; // a const field cannot be reinitialized post declaration
        static void Main(string[] args)
        {
            Console.WriteLine(PI);
        }
    }
}
Example2 : Program Corrected

using System;

namespace Console_const_keyword
{
    class Program
    {
        //constant field
        const double PI = 3.1415; // a const field cannot be reinitialized post declaration
        static void Main(string[] args)
        {
            //local variable
            double radius;
            //constant local
            const string local_const = "I am not a variable.";
            //local_const = "I cannot be reinitialized.";//error if uncommented
            radius = 100.50;
            Console.WriteLine(2*PI*radius);
            Console.WriteLine(local_const);
            //array size declaration
            const int myArraySize = 5;
            int[] myArray = new int[myArraySize];
            //initialize the array's values
            Random random = new Random();
            for (int i = 0; i < myArray.Length; i++)
            {
                myArray[i] = random.Next(10, 100);
                Console.WriteLine(myArray[i]);
            }
        }
    }
}

OUTPUT
631.4415
I am not a variable.
93
74
29
57
32

Example of use of const: We know that array is of fixed size and cannot be resized. To declare the size of an array we can use const.



No comments:

Post a Comment

Hot Topics