Structures


Structures are lightweight classes. Similar to classes, structures have behaviors and attributes. As a value type, structures directly contain their value and are stored on the stack. Because structures reside on the stack, keep them small. Do not cache large objects on the stack. The implementation of structures in C# enforces the policy of using a structure as a lightweight class. The following list details the differences between structures and classes:

  • Structures are sealed and cannot be inherited.

  • Structures cannot inherit classes and other structures.

  • Structure implicitly inherits from System.ValueType.

  • The default constructor of a structure cannot be replaced by a custom constructor.

  • Custom constructors of a structure must fully initialize the value of the structure.

  • Structures do not have destructors.

  • Field initialization is not allowed. Const members of a structure can be initialized.

Structure syntax:

  • attributes accessibility struct structname: interfacelist { structbody };

There are several attributes that target structures. Structures support the same accessibility of a class. Structures implicitly inherit System.ValueType and cannot explicitly inherit another type. However, structures can implement interfaces. Interfacelist is a list of interfaces the structure implements. The structbody encompasses the member functions and data members of the structure.

The default constructor of a structure initializes each field to a default value. You cannot replace the default constructor of a structure. Unlike a class, adding custom constructors to a structure does not remove the default constructor. Invoke a custom constructor with the new operator. The new operator will not place the structure on the managed heap. It is a call to the parameterized constructor of a structure. Structures are commonly declared without the new operator. In that circumstance, the default constructor is called.

Fraction is a structure that models naturally a fraction. Fraction has two double members. It is small and ideal for a structure.

 using System; namespace Donis.CSharpBook{     public struct Fraction {         public Fraction(double _divisor, double _dividend) {             divisor=_divisor;             dividend=_dividend;         }         public double quotient {             get {                 return divisor/dividend;             }         }         private double divisor;         private double dividend;     }     public class Calculate{         public static void Main(){             Fraction number=new Fraction(4,5);             Console.WriteLine("{0}", number.quotient);         }     } } 




Programming Microsoft Visual C# 2005(c) The Language
Microsoft Visual Basic 2005 BASICS
ISBN: 0619267208
EAN: 2147483647
Year: 2007
Pages: 161

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net