const in C#
- You have to initialize const variables while declaration.
- You cannot reassign a const variable.
- Compiler evaluates the const variables.
- The static modifier is not allowed in a constant declaration.
- A const field of a reference type other than string can only be initialized with null.
Example for const in c#.net
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
using System; using System.Text; namespace ProgramCCE { class ProgramCCE { /*A const field of a reference type other than string can only be initialized with null*/ private const StringBuilder myName = null; public static void Main() { //You have to initilize Const varabiles while declartion const int myEmpId = 173524; //Valid scenario const int myNumber = 10 + 16; const string myName = "John"; // Reassigning a const variable is not allowed. //Comment out below code to run the program myEmpId = 23456; Console.WriteLine(myEmpId); Console.Read(); } } } |
readonly in C#
- readonly fields can be initialized only while declaration or in the constructor.
- Once you initialize a readonly field, you cannot reassign it.
- 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.
Example for readonly modifier in c#.net
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
using System; using System.Text; namespace ProgramCCE { class MyClass { //readonly can only be used with instance or static variables public readonly int mynumber = 10; public readonly int addnumber = 10 + 15; //readonly modifier can be used with static varaibles public static string myEmployer = "Csharp-Console-Examples.Com"; //readonly can be used with reference types public readonly StringBuilder name = new StringBuilder("John"); /* readonly varaible can be intilized in constructor but cannot be declared in constructor */ public readonly string myName; //readonly fields can be initlized in constructor public MyClass(string name) { myName = name; } private void myMethod() { /* readonly modifier cannot be used in method level variables the below line throws a error. */ // readonly int num = 5; } } //main class class ProgramCall { public static void Main() { MyClass obj = new MyClass("Bill"); 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.