Constant and Readonly variables in c sharp

Constant Variable 


  • These variable cannot be modify once after they declaration and should be declared by keyword "const".
  • As these variable cannot be modify after declaration it is must to initialized these variables at the time of declaration only.
  • The behavior of constant variable will be similar to the behavior of a static variable that is It is initialized immediately once the execution of the class start maintaining a single copy throughout the life of the class.
  • The only difference between static and constant is static variable can be modify but not constant variables.
ReadOnly Variable 
  • The Variable are declare by only "readonly" keyword. A readonly variable cannot be modify once after its initialization and it not mandatory to initialized these variable at the time of declaration they can be initialized after declaration that is under constructor.
  • The behavior of Readonly variable will be the similar to the behavior of instance variable that is Initialized once the instance of the class is created and each and every time the instance of class created.
  • The only difference b/w Readonly and Instance variable is Instance variable can be modify but not read-only variables.
  • The only difference between constant and readonly is a constant variable is a fixed single copy for the whole class whereas the readonly variable is a fixed copy for each instance of class.
Note :     While accessing variable or fields of class from other class use class name for accessing static and constant variable or fields and the class instance for accessing instance and readonly variable or fields.




No comments:

Post a Comment