Creating Structs
You create an instance of a struct by using the new keyword in an assignment statement, just as you would for a class. In Example 7-1, the Tester class creates an instance of Location as follows:
Location loc1 = new Location( );
Here, the new instance is named loc1, and the fields are initialized to 0. The example then uses the public properties to set the values of the fields to 200 and 300, respectively.
Structs As Value Types
The definition of the Tester class in Example 7-1 includes a Location object[8] struct (loc1) created with the values 200 and 300. This line of code calls the Location constructor:
Location loc1 = new Location(200,300);
Then WriteLine( ) is called:
Console.WriteLine("Loc1 location: {0}", loc1);WriteLine( ) is expecting an object, but of course, Location is a struct (a value type). The compiler automatically wraps the struct in an object, a process called boxing (as it would any value type), and it is the boxed object that is passed to WriteLine( ). ToString( ) is called on the boxed object, and because the struct (implicitly) inherits from object, it is able to respond polymorphically, overriding the method just as any other object might:
Loc1 location: 200, 300
Tip
You can avoid this boxing by changing the preceding snippet to:
Console.WriteLine("Loc1 location: {0}",
loc1.ToString( ));You avoid the box operation by calling ToString directly on a variable of a value type where the value type provides an override of ToString.
Structs are value objects, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access