Structures

Structures are lightweight classes. Just like 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. 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 from classes or other structures.

  • A structure implicitly inherits from System.ValueType.

  • The default constructor of a structure cannot be replaced.

  • Custom constructors of a structure must initialize every field of that structure.

  • Structures cannot have destructors.

  • Fields cannot be initialized in the declaration of the structure. However, const members of a structure can be initialized.

Here is the syntax of a structure:

  • attributes accessibility struct identifier: interfacelist { body };

Structures support attributes. Actually, some attributes apply to structures explicitly—check the documentation of the attribute. Structures have the same accessibility options that a class does. Structures can implement interfaces. The structure body encompasses the member functions and fields 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 constructors with parameters to a structure does not remove the default constructor. Invoke a custom constructor with the new operator. It allows you to call a constructor other than the default constructor. The new operator will not place the structure on the managed heap. It is just another alternative to initializing the structure. Structures are commonly declared without the new operator. In that circumstance, the default constructor is called.

In the following code, Fraction is a structure that models a fraction. Fraction has two members—both doubles. The structure is small, which is ideal. The following code is an example:

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);
        }
    }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.218.151.44