C# Help - C# Community and Information

C# Structs – Introduction

January 11th, 2010 in C# Language by admin

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:
  1.  public struct Bmindex
  2.  {
  3.    double height, weight;
  4.    public Point (double height, double weight) {this.height = height; this.weight = weight;}
  5.  }
  6.  
  7.  …
  8.  Bmindex p1 = new Bmindex ();     // p1.height and p1.weight will be 0
  9.  Bmindex p2 = new Bmindex (1.8, 78); // p1.height = 1.8 p1.weight = 78

Most Commented Articles :

Leave a Reply

RSS Feed Follow Us on Twitter!