Team LiB
Previous Section Next Section

Chapter 3: Structs, Enums, Arrays, and Collections

Structs

A struct is a way to organize a group of unlike variable types under a single name. Structs are a carryover from C++. Although they are not as valuable as they once were, they still provide some usefulness in creating user-defined types (UDTs).

Structs are most useful in situations where you want the information to be stored on the stack or you do not want to incur the overhead of a class (calling an allocator and calling the constructor for the class).

Structs can be nested inside a class or a namespace. The following example includes the struct in the namespace so it will be available to all classes in the namespace. Notice how MyStruct is now a type, and an instance can be declared in the class. To access members of the class, you use the dot operator (.). The syntax is instance_name.member_ name.

Note 

It is very important to know that there are no unions in C#. This means that if you want to simulate a union in C#, you must use some built-in attributes. A sample of doing this is in Chapter 10.

Code Example: Struct
Start example

using System;

namespace Client.Chapter_3___Structs__Enums__Arrays_and_Collections
{
      //Declares a struct
      public struct MyStruct
      {
            public int MyInt;
            public long MyLong;
            public string MyString;
      }
      class Structs
      {
            static void Main(string[] args)
            {
                  //Defines an instance of a struct
                  MyStruct TheStruct;
                  TheStruct.MyInt = 0;
                  TheStruct.MyLong = 0;
                   TheStruct.MyString = "Hello World";
            }
      }
}
End example

Team LiB
Previous Section Next Section