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(200,300);

Here the new instance is named loc1 and is passed two values, 200 and 300.

Structs as Value Types

The definition of the Tester class in Example 7-1 includes a Location object, 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 boxes the struct (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

Structs are value objects, however, and when passed to a function, they are passed by value, as seen in the next line of code, in which the loc1 object is passed to the myFunc( ) method:

t.myFunc(loc1);

In myFunc new values are assigned to x and y, and then these new values are printed out:

Loc1 location: 50, 100

When you return to the calling function (Main( ) ) and call WriteLine( ) again, the values are unchanged:

Loc1 location: ...

Get Programming C# now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.