C const in detail

  • 2020-11-25 07:29:30
  • OfStack

This article illustrates the use of const in C#. Share to everybody for everybody reference. Specific usage analysis is as follows:

const is an c keyword that specifies a variable that cannot be changed. To a certain extent, using const can improve the security and reliability of the program. In addition, it is helpful to understand the role of const when viewing other people's code. In addition, const also appears in other programming languages, such as c++, php5, c#.net, hc08 c
Variables commonly modified by const 1 are read-only variables
The const definition should not change its value after it is initialized at definition time
Ex. :

const int a=1;// Can only be initialized at definition time; 
a=2;// There is an error because a Is a read-only variable
const modified 1 The use of some Pointers
int a;
const int *p=&a;// *p It's not allowed to change but p It's allowed to change
int * const p1 // Defines the 1 A read-only variable p1 ; p1 Can't be changed *p1 It can be changed

Constant declarations can declare multiple constants, such as:

public const double x = 1.0, y = 2.0, z = 3.0;

The static modifier is not allowed in constant declarations.
Constants can participate in constant expressions, as shown below:
public const int c1 = 5;
public const int c2 = c1 + 100;

Note:

The readonly keyword is different from the const keyword. The const field can only be initialized in the declaration for that field. The readonly field can be initialized in a declaration or constructor. Therefore, the readonly field may have different values depending on the constructor used. In addition, the const field is a compile time, while the readonly field can be used for run time, as shown in the following line of code:

public static readonly uint l1 = (uint)datetime.now.ticks;

I hope this article has been helpful for your C# programming.


Related articles: