In C#, the static keyword is used to declare a static field, which is a field that is shared by all instances of a class. A static field has a single value that is common to all instances of a class, and it is initialized when the class is first loaded.
The readonly keyword is used to declare a read-only field, which is a field that can only be initialized once, either at the time of declaration or in the class's constructor. A read-only field can be a static field or an instance field, and it can be accessed from any instance of the class.
The const keyword is used to declare a constant field, which is a field whose value is set at compile time and cannot be modified at runtime. A constant field can only be of one of the following types: bool, char, string, int, long, float, or double.
Here is an example of how these keywords can be used in C#:
public class MyClass
{
// A static field that is shared by all instances of the class
public static int s_staticField;
// A read-only instance field that can only be initialized in the constructor
public readonly int m_readOnlyField;
// A constant field whose value is set at compile time
public const int c_constantField = 42;
public MyClass()
{
// Initialize the read-only field in the constructor
m_readOnlyField = 123;
}
}In summary, the main differences between static, readonly, and const in C# are as follows:
static fields are shared by all instances of a class and are initialized when the class is first loaded.
readonly fields can be either static or instance fields, and they can only be initialized once, either at the time of declaration or in the class's constructor.
const fields are set at compile time and cannot be modified at runtime. They can only be of certain value types, and they must be initialized at the time of declaration.
Comments
Post a Comment