Pages

Wednesday, May 22, 2013

Readonly variable in c#

Read only variable is a run time constant.we can assign the data to the Read only variable directly while declaring the variable or
->we can assign the data to the read only in the constructor also.

Sample Code:

public partial class Readonly : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        K k = new K(20);
        K k1 = new K(30);
        Response.Write(k.x);
        Response.Write(k1.x);
        //k.x = 35; // bec we can modify the readonly value
        //k1.x = 40;
    }
}
public class K
{
    public readonly int x = 10;
    public K(int y)
    {
        x = y;
    }
}

No comments:

Post a Comment