Structs
Structs kunnen fields, methods en constructors bevatten zoals een klasse maar is een value type, geen reference type. Structs zijn value types en erven over van System.ValueType
die overerft van System.Object
.
Enkele voorbeelden van structs: int
, long
en float
zijn verkorte schrijfwijzen van de structs System.Int32
, System.Int64
en System.Single
.
Voor de verschillen tussen een struct en een klasse, zie Structs (C# Programming Guide).
Structs can also contain constructors, constants, fields, methods, properties, indexers, operators, events, and nested types, although if several such members are required, you should consider making your type a class instead. — struct (C# reference)
Voorbeelden
public struct Book
{
public decimal price;
public string title;
public string author;
}
public struct CoOrds
{
public int x, y;
public CoOrds(int p1, int p2)
{
x = p1;
y = p2;
}
}
class TestCoOrds
{
static void Main()
{
CoOrds coords1 = new CoOrds();
CoOrds coords2 = new CoOrds(10, 10);
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
*/