- Example: public const string abc = “xyz”;
- Initialized only at declaration.
- Value is evaluated at compile time and can not be changed at run time.An attempt to change it will cause a compilation error.
- Const is already kind of static.
- Since classes and structs are initialized at run time with new keyword, you can’t set a constant to a class or structure. But, it has to be one of the integral types.
Readonly Keyword:
- Example: public readonly string abc;
- Can be initialized in declaration code or consturctor code.
- Value is evaluated at run time.
- Can be declared as static or instance level attribute.
- A read only field can hold a complex object by using the new keyword at run time.
A const must be initialized at the time of its creation. A readonly field can be assigned to once in the class constructor allowing you to pass in the value at run-time. With Const fields, the compiler performs some optimization by not declaring any stack space for the field.
Constant means - > if you want to define something at compile time . after that u can't change that value that .....
Readonly means - > if you don't know value at compile time but u can find that at runtime that time u can use readonly ..
No comments:
Post a Comment