C# Structs – Introduction

A Struct  is very similar to a Class,  however whereas a Class is a reference type  a Struct is a value type. Also, Classes support inheritance whereas Structs do not.

In practice Structs are a lightweight class which are often used for numeric types. As they are a value type, each instance does not require instantiation of an object on the heap.

Structs must has parameters in the constructor but cannot have a finalizer or virtual members. Instantiating a constructor can be done without providing parameters which just sets them to zero.

Example:

//Struct Example:
	public struct Bmindex
	{
	  double height, weight;
	  public Point (double height, double weight) {this.height = height; this.weight = weight;}
	}

	...
	Bmindex p1 = new Bmindex ();     // p1.height and p1.weight will be 0
	Bmindex p2 = new Bmindex (1.8, 78); // p1.height = 1.8 p1.weight = 78
Twitter Digg Delicious Stumbleupon Technorati Facebook Email

No comments yet... Be the first to leave a reply!