This website completely moved to new platform. For latest content, visit www.programmingposts.com

Search this Site

1 Oct 2013

Declaring constants in C#.NET

In this article we will see a small example of using constants in c#. constants are declared with a keyword const .

> The program below is to find the area and perimeter of circle in which we use const . 
> In the program below we have declared PI as a constant whose value is given as 3.14 
   It means PI value cannot be changed either at compile time or run-time .

> Any Integral or string variables can be declared as constants.
   We can also declare constants as public to use it in all the classes in a program.

using System;

namespace Constants
{
    class Program
    {
        static void Main(string[] args)
        {
            //declaring const variable PI
            const double PI = 3.14;
            Console.WriteLine("*** www.ProgrammingPosts.blogspot.com ***");
            Console.WriteLine(">>> c# Program to find Area and Perimeter of Circle <<< \n");
            Console.Write("Enter radius value: ");
            int r = Convert.ToInt32(Console.ReadLine()); //taking radius as input
            double area = PI * r * r; //getting area of circle
            Console.WriteLine("Are of circle is: " + area);
 
            //if we try to assign a value to PI , we get compile-time error
            //PI = 123;

            double perimeter = 2 * PI * r; //getting perimeter of circle
            Console.WriteLine("Perimeter of circle: " + perimeter);
          
            Console.Read();
        }
    }
}

Sample Output :