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:
using System;
using System.Text;
namespace ProgramCAll
{
class ProgramCall
{
private const StringBuilder myName = null;
public static void Main()
{
const int myEmpId = 173524;
const int myNumber = 10 + 16;
const string myName = "John";
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:
using System;
using System.Text;
namespace ProgramCall
{
class MyClass
{
public readonly int mynumber = 10;
public readonly int addnumber = 10 + 15;
public static string myEmployer = "ProgramCall.Com";
public readonly StringBuilder name = new StringBuilder("John");
public readonly string myName;
public MyClass(string name)
{
myName = name;
}
private void myMethod()
{
}
}
class ProgramCall
{
public static void Main()
{
MyClass obj = new MyClass("Bill");
Console.Read();
}
}
}