Search This Blog

Tuesday, November 27, 2012

readonly c#

C# > Modifiers > readonly

Readonly prevents a field to be changed.

When a field declaration includes a readonly modifier, assignments to the field introduced by the declaration can only occur as part of the declaration or in a constructor in the same class.

Readonly fields can be initialized at runtime, unlike const.

Example 1:
            public readonly int x = 10;

Example 2:
    public partial class Form1 : Form
        {
            public class Stack
            {
                readonly int m_Size;
                public Stack()
                    : this(20)
                { }
                public Stack(int size)
                {
                    m_Size = size;
                }
            }
            public Form1()
            {
                InitializeComponent();
            }
            private void Form1_Load(object sender, EventArgs e)
            {
                Stack st = new Stack();
            }
        }