using System;
namespace ConsoleApplication1
{
class constDemo
{
public const int x = 25;
// cannot mark as static, by default const is static
//public static const int b=50;
}
class Program
{
static void Main(string[] args)
{
const int intVar=10;
//Cannot reassigns the value.
//Error:The left-hand side of an assignment must be a variable, property or indexer
//intVar = 40;
Console.WriteLine(intVar);
// x variable is by default constant. Therefore called by the class name.
Console.WriteLine("x = " + constDemo.x);
// Error: The expression being assigned to 'value' must be constant
// Here length is not constant.
int length = 5;
//const int value = 10 + length;
Console.ReadLine();
}
}
}
using System;
namespace ConsoleApplication1
{
class MyClass
{
readonly int intVar = 25; // initialized at the time of declaration
readonly int readOnlyVar;
public MyClass(int x)
{
readOnlyVar = x; // initialized at run time
Console.WriteLine("readOnlyVar = " + readOnlyVar);
}
public void SetData()
{
// It will give the compile time error.
// You cannot set the value in function.
//readOnlyVar = 100;
// intVar has already initialized.
Console.WriteLine("intVar = " + intVar);
}
}
class Program
{
static void Main(string[] args)
{
MyClass obj = new MyClass(30);
obj.SetData();
Console.ReadLine();
}
}
}
const | readonly |
---|---|
Must be initialized at the time of declaration of the field. | Initialized at the time of declaration or the constructor of the class |
By default const fields are static | By default readonly fields are not static. It can use with static modifier. |
You cannot reassign a const variable. | You can reassign a const variable in constructor. |
It is called as compile time constant | It is called as run time constant |
Can be declared in function. | Cannot declare in function. |