Structs
A struct (or structure) is a value type which encapsulates a small group of related variables.
Structs prove efficient in certain situations; for example, an application requiring a declaration of an array with 2,000 objects of the same type allocates too much memory. They represent a record; for example, a laser cutter with a model name, model number, type, and product ID number. Structs can hold constructors, fields, constants, methods, indexers, events, properties, operators, and nested types; however, if several members are necessary, a class would be more appropriate. Review struct syntax below:
public struct Pizza { public float price; public string name; public string size; }
Review the example below to see the struct in use:
using System; struct Pizza { private float price; private string name; private string size; private int productID; public void getInfo(string n, string s, float p, int pi) { price = p; name = n; size = s; productID = pi; } public void show() { Console.WriteLine(name + ”{0}” + size + “{0}” + “$” + price); } } public class PizzaTest { public static void Main(string[] args) { Pizza Pizza1 = new Pizza(); Pizza Pizza2 = new Pizza(); Pizza1.getInfo("The Californian",”Medium”, "15.00"); Pizza2.getInfo("Soul Food","Medium", "25.00"); Pizza1.show(); Pizza2.show(); Console.ReadKey(); } }
Structs have the following limitations:
- Though they can implement interfaces, structs cannot inherit; thus, they cannot have protected members.
- Defining a default (no parameters) constructor for a struct causes an error.
- Initializing an instance field within a struct body causes an error.
SEPARATING CLASSES AND STRUCTS
Knowing when to use structs rather than classes may be unclear. Classes and structs are separated by the following characteristics:
- Structs, unlike classes, do not require the new operator in instantiation.
- Structs, unlike classes, cannot inherit or serve as a base class; however, structs inherit from the base class Object.
- Structs are value types, and classes are reference types. Classes cannot be declared as structs.
- Structs are best for small, simple datasets; and classes are better for large, complex sets.