Structs
A struct in C# is similar to a class, but it is intended for smaller data structures. A struct is a value type, whereas a class is a reference type. Each struct object contains its own copy of the data, whereas a class object contains only a reference to the data. For more information, see Value Types (C# Reference) and Reference Types (C# Reference).
All struct types inherit from the Object class, which is a root class in C#. You cannot inherit from a struct, although a struct can implement interfaces.
A struct typically can be created faster than a class. If in your application new data structures are being created in large numbers, you should consider using a struct instead of a class. Structs are also used to encapsulate groups of data fields such as the coordinates of a point on a grid, or the dimensions of a rectangle. For more information, see Classes.
Example
The following example defines a struct to store a geographic location. It also overrides the ToString() method of the Object class to produce a more useful output when displayed in the WriteLine statement.
struct GeographicLocation
{
private double longitude;
private double latitude;
public GeographicLocation(double longitude, double latitude)
{
this.longitude = longitude;
this.latitude = latitude;
}
public override string ToString()
{
return System.String.Format("Longitude: {0} degrees, Latitude: {1} degrees", longitude, latitude);
}
}
class Program
{
static void Main()
{
GeographicLocation Seattle = new GeographicLocation(123, 47);
System.Console.WriteLine("Position: {0}", Seattle.ToString());
}
}
Output
The output from this example looks like this:
Position: Longitude: 123 degrees, Latitude: 47 degrees
See Also
Concepts
Reference
Classes and Structs (C# Programming Guide)
Change History
Date |
History |
Reason |
---|---|---|
October 2008 |
Updated struct description in the introduction. |
Customer feedback. |