A struct type is a value type that can contain constructors, constants, fields, methods, properties, indexers, operators, and nested types. The declaration of a struct takes the following form:
[attributes] [modifiers] struct identifier [:interfaces] body [;]
The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.
It is an error to declare a default (parameterless) constructor for a struct.
It is an error to initialize an instance field in a struct.
Unlike C++, you cannot declare a class using the keyword struct. In C#, classes and structs are semantically different. A struct is a value type, while a class is a reference type. For more information on features of value types, see Value Types.
For more information on struct, see Structs in the language reference.
This example demonstrates struct initialization using both default and parameterized constructors.
// struct declaration and initialization using System; public struct Point { public int x, y; public Point(int p1, int p2) { x = p1; y = p2; } } class MainClass { public static void Main() { // Initialize: Point myPoint = new Point(); // Default constructor Point yourPoint = new Point(10,10); // Parameterized constructor // Display results: Console.Write("My Point: "); Console.WriteLine("x={0}, y={1}", myPoint.x, myPoint.y); Console.Write("Your Point: "); Console.WriteLine("x={0}, y={1}", yourPoint.x, yourPoint.y); } }
My Point: x=0, y=0 Your Point: x=10, y=10
This example demonstrates a feature that is unique to structs. It creates a Point object without using the new operator. If you replace the word struct with the word class, the program won't compile.
// Declare a struct object without "new" using System; public struct Point { public int x, y; public Point(int x, int y) { this.x = x; this.y = y; } } class MainClass { public static void Main() { // Declare an object: Point myPoint; // Initialize: myPoint.x = 10; myPoint.y = 20; // Display results: Console.WriteLine("My Point:"); Console.WriteLine("x = {0}, y = {1}", myPoint.x, myPoint.y); } }
My Point: x = 10, y = 20
C# Keywords | Default Values Table | Built-in Types Table | Types Categories | Value Types