Pages

Monday, May 13, 2013

constan in c#

->In c# we can declare the constants by ussing "const" keyword
->In c# only data assign to a constant we can not change the value of the constant(constant value should assign during compile time only)

Sample code:

public partial class Constant : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Doctor d1 = new Doctor(20, "rajesh");
        Doctor d2 = new Doctor(45, "dipak");
        Response.Write(d1.age);
        Response.Write(d1.name);
        Response.Write(d2.age);
        Response.Write(d2.name);
        Response.Write(Doctor.address); // using class name we can print the constant value
    }
}
public class Doctor
{
    public int age;
    public string name;
    public const string address = "btm,bangalore";
    public Doctor(int age, string name)
    {
        this.age = age;
        this.name = name;
    }
}
Note:
   ex: we can not use this type
    public class A
     {
    public int x=10;
     public const int y=20+30; // here compiler will be responseble to give the value of Y
     public  const int z=x+x;// it will not work bec top x may be change in future
      

No comments:

Post a Comment