C Sharp Constant
Constants:
Constant is variable of a class of which the value remain
fixed.They are declared without using static keyword. we can use a constant in
the class in which it is defined, referring to it by name. we can also
use the constant in other classes, prefixing
the name of the constant with the class name. it's mandatory to assign a value to it. By
default a constant is static and we cannot change the value of a constant
variable throughout the entire program. Constants can be of any of the
basic data types like an integer constant, a floating constant, a character
constant, or a string literal.
Defining Constants
Constants are defined using the const keyword. Syntax for defining
a constant is:
const <data_type>
<constant_name> = value;
Ex.
const double Pi =
3.14159;
const double Rvalue
= 1.8766;
const string Name =
"Suhail Osmani";
We cannot include the static
keyword when declaring a constant. A constant by default static, so the static
keyword would be will generate an error
if you use before it.
/ This is Correct
const string Remarks
= "Exellent";
// This is incorrect
static const int Age =
42;
Defining
Contant inside Class : We can define a constant within a class that
contains related data and methods or a class, containing a collection of constants.
public class contants
{
Public const double Pi = 3.14159;
Public
const double Rvalue
= 1.8766;
Public
const string Name =
"Suhail Osmani";
}
Initialization
of a Constant
`
A
constant must be initialized at time of decalaration . Otherwise, it will give an error like "A const field requires a
value to be provided
// This is Correct
const string Remarks = "Exellent";
// This is incorrect
const string Remarks;
Using Constant in Program: Let us use a
constant in a program to clarify a constant
using System;
namespace DeclaringConstants
{
class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;
// constant declaration
double r;
Console.WriteLine("Enter Radius of Circle: ");
r = Convert.ToDouble(Console.ReadLine());
double Circle_Circumfrence = 2 * pi * r;
Console.WriteLine("Radius: {0}, Circumfrence: {1}", r, Circle_Circumfrence);
Console.ReadLine();
}
}
}
Output:Enter Radius:
3
Radius: 3, Circumfrence: 18.84954
C Sharp Constant
Reviewed by Admin
on
08:15:00
Rating:
No comments: