Home > Article > Backend Development > Introduction to C# basics-detailed explanation of constants
This article mainly introduces the relevant knowledge of constants in C#, which has a good reference value. Let’s take a look with the editor below
Constant, as the name suggests, is a “quantity that does not change”.
The numbers (such as 12.85), characters (such as 'F'), and strings (such as "Thank you") that we usually write are all "literal constants".
There are some constants that are both important and error-prone. For example, the value of pi is 3.1415926..., so we often use custom constants. For example:
namespace Test { class Program { static void Main(string[] args) { const double PI = 3.1415926;//自定义常量PI,表示圆周率 Console.Write(“半径为4的圆的周长为:”);//字符串常量 Console.WriteLine(2*PI*4);//应用自定义常量PI Console.Write(“半径为4的圆的面积为:”);//字符串常量 Console.WriteLine(PI*4*4);//应用自定义常量PI } } }
const keyword indicates that PI is a constant; double keyword indicates that the type of PI is "double precision floating point type " (a high-precision number type ).
This code uses pi (circumference, area) twice, but because a custom constant is used, the literal constant 3.1415926 is only written once. This avoids errors caused by repeated writing.
Running effect:
Another point to note: constants are assigned values when they are declared and cannot be modified later.
Using constants, it seems that the identity of the protagonist can be set in the game. For example:
namespace Test { class Program { static void Main(string[] args) { const string CITY = "某城市";//常量,城市 const string NAME = "凯文";//常量,姓名 Console.WriteLine(NAME+"出生在"+CITY+"的一个普通家庭");//使用常量 } } }
The running result is:
Kevin was born in a certain city An ordinary family
The above is the detailed content of Introduction to C# basics-detailed explanation of constants. For more information, please follow other related articles on the PHP Chinese website!