Struct Type

.Struct Example Program Output


Struct Example Program Output

.Struct Type

"A C# example program to illustrate the use of the struct type. The struct type is one of the two commonly used constructs to create custom types. A struct is a value type, stored on the stack, and can contain constants, fields, properties, indexers, methods, events, and static members."

Both the class and struct constructs are used to create custom types by encapsulating a set of data and behaviors that belong together as a logical unit. Generally, a class is used to model more complex behavior, or contains data which is intended to be modified after the class object is created. Where as a struct is used for small data structures that primarily contain data which is not intended to be modified after the structure is created. Microsoft specifies the following set of characteristics to help determine when using a struct, rather than a class, is appropriate.

A type should have all four of these characteristic to be defined using a struct:

  1. The type will have an instance size of 16 bytes or less.
  2. The type will be immutable.
  3. The type will logically represents a single value, similar to primitive types (int, double, etc.) Typical example of a struct is a point (x,y,z).
  4. The type will not have to be boxed frequently.

The major difference between a class and a struct is that a class is a reference type while a struct is a value type. When a class is instantiated, the class variable holds a memory reference to the class data which resides in the heap. When a struct is instantiated, a struct variable holds the actual data which resides on the stack.

Additional differences between a struct and a class include:

  1. Struct can declare constructors, but they must have parameters. A default constructor (no parameters) is not allowed for a struct.
  2. Inheritance is not allowed with struct (other than from the base object class). Structs are inherently sealed.
  3. Both struct and class can use "new" operator to create an instance. However a struct can also be created without the "new" operator. When a struct is instantiated without the "new" operator, all the fields must be public and you must initialize all the fields yourself.
  4. Events declared in a class are automatically locked to make them thread safe. Events declared in a struct are not automatically locked.
  5. A class can contain volatile fields, while a struct can not.

The example struct program creates a Rectangle type using a struct. The Rectangle type contains a string array, a static index variable, auto-implemented properties, and methods. The Rectangle struct uses an object initializer when it is instantiated. The main method creates four rectangles of different sizes with the color indexing through the string array of colors. The following C# features are used in the example code:

  1. struct - Microsoft Developer Network (MSDN)
  2. fields - Microsoft Developer Network (MSDN)
  3. auto-implemented fields - Microsoft Developer Network (MSDN)
  4. properties - Microsoft Developer Network (MSDN)
  5. String.split() method - Microsoft Developer Network (MSDN)
  6. static modifier - Microsoft Developer Network (MSDN)
  7. object initalizer - Microsoft Developer Network (MSDN)


Struct Type

namespace Rectangles
{
    struct Rectangle
    {
        // Array of Colors
        static string[] color = "Red Green Blue".Split() ;
        static int colorIndex = 0;

        // Next Color Getter
        public string nextColor
        {
            get { return color[colorIndex]; }
        }

        // Width Property Auto-Implemented
        public int Width { get; set; }

        // Height Property Auto-Implemented
        public int Height { get; set; }

        // Method to Increase Height and Width of Rectangle
        public void MakeBigger()
        {
            Width *= 2;
            Height *= 2;
        }

        // Method to Draw Rectangle on Screen
        public void DrawRectangle()
        {
            System.Console.Write(' ');
            for (int i = 0; i < Width; i++)
                System.Console.Write('-');
            System.Console.WriteLine();

            for (int i = 0; i < Height; i++)
            {
                System.Console.Write('|');
                for (int j = 0; j < Width; j++)
                    System.Console.Write(' ');               
                if (i ==0)
                    System.Console.WriteLine("| This is a {0} x {1} rectangle in: {2}", Width, Height, nextColor);
                else
                    System.Console.WriteLine('|');
            }

            System.Console.Write(' ');
            for (int i = 0; i < Width; i++)
                System.Console.Write('-');
            System.Console.WriteLine();

            // Update color index
            if (colorIndex < 2)
                colorIndex++;
            else
                colorIndex = 0;
        }
    }

    class Program
    {
        static void Main()
        {
            // Create first rectangle, test MakeBigger method, print characteristics, draw on screen
            Rectangle myRectangle = new Rectangle { Width = 4, Height = 3};  // With Object Initializer
            System.Console.WriteLine("Width is: {0} and height is: {1}", myRectangle.Width, myRectangle.Height);
            myRectangle.MakeBigger();
            System.Console.WriteLine("Width is: {0} and height is: {1}", myRectangle.Width, myRectangle.Height);
            System.Console.WriteLine("The color of the next rectangle will be: {0}", myRectangle.nextColor);
            System.Console.WriteLine();
            myRectangle.DrawRectangle();

            // Create second rectangle in size specified using next color, draw on screen
            Rectangle myRectangle2 = new Rectangle { Width = 4, Height = 3 };           
            myRectangle2.DrawRectangle();

            // Create third rectangle in size specified using next color, draw on screen
            Rectangle myRectangle3 = new Rectangle { Width = 2, Height = 2 };
            myRectangle3.DrawRectangle();

            // Create fourth rectangle in size specified using next color, draw on screen
            Rectangle myRectangle4 = new Rectangle { Width = 1, Height = 1 };
            myRectangle4.DrawRectangle();
        }
    }
}