Pages

Wednesday, May 15, 2013

Struct in c#

1>Struct is just like a class but its is light weight and faster.
2>Within struct  declaration , fields can not be intialize but we can declare in anotherway like ussing "const","static" and readonly.
3>Default constructor or destructor not allowed in the class.
4>All the struct are inherited from directly from "system.valuetype" ,which is inherited from "system.object".
5>we can not inherit struct from other struct.
6>:Bydefult it is sealed (valu type faster that ref type).

Note:

Parameterized consructor not allowed in structu(but some case allowed like when we pass the value to in construct in main object at the time object creation)

Q).Q:When we declare a struct in PG?

ans :Better to declare a struct when the total size of all fields is less tha 16 Byte(not a rule but faster speed)

Sample code1:

public partial class Struct : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        I i = new I(30, 40);//this value only for consrructor
        H h = new H(20, 30);
        Response.Write(i.x + "<br/>" + i.y + "<br/>");
        Response.Write(h.x + "<br/>" + h.y + "<br/>");
     }
}
public struct H
{
    public int x;
    public int y;
    public H(int x, int y) // defination's rule no parameterize construcutor but we r pass the the value for this in object create time(30,40)
    {
        this.x = x;
        this.y = y;
    }
}
public class I
{
    public int x;
    public int y;
    public I(int x,int y)
    {

        this.x=x;

        this.y=y;
    }
}

Sample code2:

//public struct A
//{
//    public int x;//alloewd
//    public string y = "palle";// not allowed
//    public bool b = true;//not allowed
//    public int m(int a, int b)//allowed
//    {
//        return a + b;
//    }
//}
//public struct B

//{
//    public const int x = 10;//allowed
//    public static int y = 20;//allowed
//    public readonly int z = 40;//allowed
//    public B() //Not allowed(bec parameteried constructor)
//    {

//    }
//}

No comments:

Post a Comment