Structs in C# - ablealias/asp.net GitHub Wiki
The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color
public struct CoOrds
{
public int x, y;
public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
Class vs Struct
Structs share most of the same syntax as classes, although structs are more limited than classes:
- Within a struct declaration,
fields cannot be initialized unless they are declared as const or static
. - A struct
cannot declare a default constructor
(a constructor without parameters) or a destructor. - Structs are copied on assignment. When a struct is assigned to a new variable, all the data is copied, and any modification to the new copy does not change the data for the original copy. This is important to remember when working with collections of value types such as Dictionary<string, myStruct>.
Structs are value types and classes are reference types.
- Unlike classes, structs
can be instantiated without using a **new** operator
. - Structs
can declare constructors that have parameters
. - A struct
cannot inherit from another struct or class
, and it cannot be the base of a class. All structs inherit directly from System.ValueType, which inherits from System.Object. - A struct
can implement interfaces
. - A struct can be used as a nullable type and can be assigned a null value.
Example
// Declare and initialize struct objects.
class TestCoOrds
{
static void Main()
{
// Initialize:
CoOrds coords1 = new CoOrds();
CoOrds coords2 = new CoOrds(10, 10);
// Display results:
Console.Write("CoOrds 1: ");
Console.WriteLine("x = {0}, y = {1}", coords1.x, coords1.y);
Console.Write("CoOrds 2: ");
Console.WriteLine("x = {0}, y = {1}", coords2.x, coords2.y);
// Keep the console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
}
}
/* Output:
CoOrds 1: x = 0, y = 0
CoOrds 2: x = 10, y = 10
*/