What is difference between constants, readonly and static variable?
Hello guys,today we are going to learn very confusing topic.Among these static is strength forward.We will understand them one by one,so lets start with static variable.
Static Keyword
The static keyword is used to make a static member, which means static members are common to all the objects which means a static member is shareable among all objects. (memory is allocated only once).This keyword can be used with classes, fields, methods, properties, operators, events, and constructors, but it cannot be used with indexers, destructors, or types other than classes.
Key points need to be remember for Static keyword
- If the static keyword is applied to a class, all the members of the class must be static.
- Static methods can only access static members of same class. Static properties are used to get or set the value of static fields of a class.
- Static constructor can't be parameterized. Access modifiers can not be applied on Static constructor, it is always a public default constructor which is used to initialize static fields of the class.
Const Keyword
Const keyword is used to declare constant field.Constant fields or local variables must be assigned a value at the time of declaration and after that they cannot be modified. By default constant are static, hence you cannot define a constant type as static.
Readonly Keyword
Readonly is the keyword whose value we can change during runtime or we can assign it at run time but only through the non-static constructor
We can define a readonly field as static member since, like constant by default it is not static. Readonly keyword can be apply to value type and reference type (which initialized by using the new keyword) both. Also, delegate and event could not be readonly.
Use the readonly modifier when you want to make a field constant at run time.
Hope you like this tutorial.Please provide your feedback.
Thanks.
What is difference between constants, readonly and static variable?
Reviewed by CodiBucket
on
13:09
Rating:
No comments: