Structure is a user-defined value type which encapsulates member data and member function.
A struct is a user-defined value type. It is declared in a very similar way to a class, except that it can’t inherit from any class, nor can any class inherit from it (as mentioned\ previously, however, all value types do inherit from System.object), The following example shows a partial declaration for a ‘Coordinate’ struch.
struct Coordinate
{
pub1i c int x;
public int y;
public Coordinate(int x, int y)
{
this . x = x;
this.y = y;
}
}
Given the above, one could initialise a Coordinate type in a familiar way, using code like:
coordinate c = new coordinate(10, 2);
~ Concept
Note that if a variable of a struct type is declared without being given an explicit value, eg:
Coordinate c2 ;
it does not equate to ‘null’ (this being the default value for reference types, rather than value types. Instead, the variable is initialised to a state where its fields have their default values.If these fields are basic value types, they will generally be set to zero. If these field they will be set to ‘null’.
Because of this default initialization behaviour, it is an error for a struct to be given a parameterless constructor (eg. one like ‘public Coordinate().) Also, where a struct does have a constructor, you should be sure to make assignments to all of the struct’s fields within this constructor.
Use of structure
using system;
public struct Storeitem
{
public long ItemNumber;
public string ItemName;
public double unitprice;
public void DisplayAnltem()
{
console.writeLine(“Department store”);
console.writeLine(“Item #: {0}”, this.ltemNumber);
console.writeLine(“Description: {0}”, this.ItemName);
Console.writeLine(“unit price: {0:C}\n”, this.unitprice);
}
}
public class Exercise
{
static void Main()
{
Storeltem item = new Storeltem ();
item.ltemNumber = 348649;
item.ItemName = “Men 3-piece Jacket”;
item.unitprice = 275.95;
item.DisplayAnltem ();
}
}
OUTPUT:
Department Store
Item #: 348649
Description: Men 3-piece Jacket
unit price: 275.95