by Dinesh Thakur Category: Introduction to C#

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



About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.SC (Computer Science), MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.