By ussing static constracutor we can intialize the static variable
*we can not use access modifier(public,private..) by declaring static constructor
*Static constructor can not take parameter.
*we can not use access modifier(public,private..) by declaring static constructor
*Static constructor can not take parameter.
Sample code 1:
public partial class static_constructor : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Doctor d1=new Doctor(50,"ramesh");
Doctor d2=new Doctor(55,"bikash");
Response.Write(d1.age);
Response.Write(d1.name);
Response.Write(d2.age);
Response.Write(d2.name);
Response.Write(Doctor.address);
}
}
public class Doctor
{
public int age;
public string name;
public static string address; // here all doctor address is same then we need 3 time declare hence we use static constructor
public Doctor(int age, string name)
{
this.age = age;
this.name = name;
}
static Doctor() // this is called static constructor( not taken any access modifier)
{
address = "Bangalore";
}
}
{
protected void Page_Load(object sender, EventArgs e)
{
Doctor d1=new Doctor(50,"ramesh");
Doctor d2=new Doctor(55,"bikash");
Response.Write(d1.age);
Response.Write(d1.name);
Response.Write(d2.age);
Response.Write(d2.name);
Response.Write(Doctor.address);
}
}
public class Doctor
{
public int age;
public string name;
public static string address; // here all doctor address is same then we need 3 time declare hence we use static constructor
public Doctor(int age, string name)
{
this.age = age;
this.name = name;
}
static Doctor() // this is called static constructor( not taken any access modifier)
{
address = "Bangalore";
}
}
Sample code2 :
public partial class static_constructor2 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
A a1 = new A(21);
Response.Write(a1.y);
}
}
public class A
{
private static int x;
static A()
{
x = 20;
}
public int y;
public A(int y)
{
this.y = y;
}
}
public class B : A
{
public static int x1;
public int y1;
public B(int y1):base(y1) // here if u supposed to not write base keyword it will not be work
{
this.y1 = y1;
}
No comments:
Post a Comment