Constant (const) and Readonly (readonly) both looks like same as per the uses but they have some differences:
Constant is known as “const” keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.
Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with “new” keyword.
See the example
We have a Test Class in which we have two variables one is readonly and another is constant.
Constant is known as “const” keyword in C# which is also known immutable values which are known at compile time and do not change their values at run time like in any function or constructor for the life of application till the application is running.
Readonly is known as “readonly” keyword in C# which is also known immutable values and are known at compile and run time and do not change their values at run time like in any function for the life of application till the application is running. You can assay their value by constructor when we call constructor with “new” keyword.
See the example
We have a Test Class in which we have two variables one is readonly and another is constant.
- class Test {
- readonly int read = 10;
- const int cons = 10;
- public Test() {
- read = 100;
- cons = 100;
- }
- public void Check() {
- Console.WriteLine("Read only : {0}", read);
- Console.WriteLine("const : {0}", cons);
- }
- }
So finally remove that line of code from class and call this Check() function like the following code snippet:
- class Program {
- static void Main(string[] args) {
- Test obj = new Test();
- obj.Check();
- Console.ReadLine();
- }
- }
- class Test {
- readonly int read = 10;
- const int cons = 10;
- public Test() {
- read = 100;
- }
- public void Check() {
- Console.WriteLine("Read only : {0}", read);
- Console.WriteLine("const : {0}", cons);
- }
- }
No comments:
Post a Comment