Saturday, May 22, 2010

Differences between 'const' and 'read-only' in C#

ConstRead-Only
  • Can't be static.
  • Value is evaluated at compile time
  • Initialized at declaration only
  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in
    the constructor.
Example on Const and Read-Only

public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
class constvalue
{
public const int conval = 10; //constant initialization
public readonly int tempvalue = conval; //read-only initialization
public constvalue(int rvalue)
{
tempvalue = tempvalue + rvalue; //read-only initialization in constructor
MessageBox.Show(tempvalue.ToString());
}
}

private void button1_Click(object sender, EventArgs e)
{
constvalue objconstvalue = new constvalue(100);
}

}

0 comments:

Post a Comment