Constants
- Constants are static by default.
- They must have a value at compilation-time (you can have e.g. 3.14 * 2 + 5, but cannot call methods).
- Could be declared within functions.
- These are copied into every assembly that uses them (every assembly gets a local copy of values).
- using System;
- namespace ConstantExample
- {
- class ConstantExample
- {
- private const int PI = 3.14;
- public static void Main()
- {
-
- const int RollNo = 1284;
-
- const int Age = 10 + 13;
- const string Name = "Satish Kumar";
-
-
- RollNo = 1405;
- Age++;
- Console.WriteLine(Name);
-
- Console.Read();
- }
- }
- }
Readonly
- Must have set value, by the time constructor exits.
- Are evaluated when instance is created.
- You can use static modifier for readonly fields.
- readonly modifier can be used with reference types.
- readonly modifier can be used only for instance or static fields, you cannot use readonly keyword for variables in the methods.
- using System;
-
- namespace ReadOnlyExample
- {
- class ReadOnlyTest
- {
-
- readonly int RollNo = 1284;
-
-
- readonly int Age;
-
- readonly string Name = "Satish Kumar";
-
-
- public ReadOnlyTest (string name)
- {
- Age = 23;
- Name = name;
- }
-
- public changeName(string newName)
- {
- Name = "Satish Kumar Vadlavalli"; ;
- }
- }
-
- class ReadOnlyExample
- {
- public static void Main()
- {
- ReadOnlyTest obj = new ReadOnlyTest("Satish");
- Console.Read();
- }
- }
- }
Difference between const and readonly
- const fields has to be initialized while declaration only, while readonly fields can be initialized at declaration or in the constructor.
- const variables can declared in methods ,while readonly fields cannot be declared in methods.
- const fields cannot be used with static modifier, while readonly fields can be used with static modifier.
- A const field is a compile-time constant, the readonly field can be used for run time constants.
A blog without comments is not a blog at all, but do try to stay on topic. Please comment if you have any questions or leave your valuable feedback. Happy Learning.