Wednesday 30 May 2007

Structures in c#

A structure in c# is at first sight the same as a class, but there are differences, which I will describe in the following, but first the structure of the structure:


Structure:
A structure in c# has the following form:


<modifiers >
struct<struct_name>
{
//Structure members
}

or an actual example

struct Weight
{
public int
value;
public string
unit;
}


And is instantiated like this:

Weight ms = new Weight();

Unlike classes, the struct object can also be created without using the new operator.

Weight ms;

But in this case all fields of the struct will remain unassigned and the object can't be used until all of the fields are initialized.
At the bottom I have attached a larger example of a structure.


Properties of a Structure:

A structure can contain
fields, methods, constants, constructors, properties, indexers, operators and even other structure types.

It is even possible for a structure to implement a interface or inherit from another structure.

interface PhysicalUnit
{
public int getValue()
}


struct weight : PhysicalUnit
{
private int value
public int getValue(){
return value
}


The difference:
The difference between a structure and a class is the place it is put in memory. Because as we all know an object of a class type is put in the heap, with a reference (pointer
) on the stack which points to the object. An object of structure type on the other hand is placed on directly on the stack.

Example:

Below is an example of a structure which shows how a constructor, properties ect.

using
System;
struct
Complex
{
private int
x;
private int
y;
public Complex(int i, int
j)
{
x = i;
y = j;
}
public void
ShowXY()
{
Console.WriteLine("{0} {1}",x,y);
}
public static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}
}
class
MyClient
{
public static void
Main()
{
Complex c1 = new
Complex(10,20);
c1.ShowXY();
// displays 10 & 20
Complex c2 = new
Complex();
c2.ShowXY();
// displays 0 & 0
c2 = -c1;
c2.ShowXY();
// diapls -10 & -20
}
}


Operator overload
It example above also includes an example of an operator,

public
static Complex operator
-(Complex c)
{
Complex temp = new
Complex();
temp.x = -c.x;
temp.y = -c.y;
return
temp;
}


which is new to me from the Java world. but a nice feature, which should be used
carefully, since in this example its quite intuitive what happens if you take one element and subtracts it from another. But in more complex types of structures this can be more misguiding than helpful.


No comments: