Thursday, 26 July 2012

Structures In C Sharp


Structures in C#

A structure allows you to create your own custom data types and it contains one or more members that can be of different data types. It can contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types . Structures are very similar to classes but there are some restrictions present in the case of structures that are absent in the case of classes.
For example you cannot initialize structure members. Also you cannot inherit a structure whereas classes can be inherited. Another important feature of structures differentiating it from classes is that a structure can't have a default parameter-less constructor or a destructor. A structure is created on the stack and dies when you reach the closing brace in C# or the End structure in VB.NET.
But one of the most important differences between structures and classes is that structures are referenced by value and classes by reference. As a value type, allocated on the stack, structs provide a significant opportunity to increase program efficiency. Objects on the stack are faster to allocate and de-allocate. A struct is a good choice for data-bound objects, which don’t require too much memory. The memory requirements should be considered based on the fact that the size of memory available on the stack is limited than the memory available on the heap. Thus we must use classes in situations where large objects with lots of logic are required.

struct initialized using both default and parameterized constructors


using System;
public struct Point
{
public int x, y;
public Point(int p1, int p2)
{
x = p1;
y = p2;
}
}

class MainClass {
public static void Main()
{
Point myPoint = new Point();
Point yourPoint = new Point(10,10);
Console.Write("My Point: ");
Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
Console.Write("Your Point: ");
Console.WriteLine("x = {0}, y = {1}", yourPoint.x, yourPoint.y);
}
}

struct initialized without using new operator


public struct Point
{
public int x, y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
}
class MainClass
{
public static void Main()
{
Point myPoint;
myPoint.x = 10;
myPoint.y = 20;
Console.WriteLine("My Point:");
Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y);
}
}



No comments:

Post a Comment