C#/C# Tutorial

C# Constants | C# Tutorial for Beginners

DragonTory 2023. 2. 14. 20:19
반응형

 C# Constants 

Constants are variables whose values cannot be changed once they are assigned.

They are declared using the "const" keyword and can only be assigned a value at the time of declaration.

Constants are typically used to define values that will remain fixed throughout the execution of a program, such as mathematical constants or values that are used frequently throughout the code.

 

Here's an example of how to declare and use a constant in C#:

1
2
3
4
5
const double PI = 3.14159;
double radius = 5;
double circumference = 2 * PI * radius;
Console.WriteLine($"The circumference of a circle with radius {radius} is {circumference}");
 
cs

 

In this example, the constant PI is declared with a value of 3.14159 using the const keyword. 

The constant is then used in a calculation to find the circumference of a circle with a given radius. 

Since PI is a constant, its value cannot be changed throughout the execution of the program, ensuring that the result of the calculation will always be accurate.




반응형