## Using Structures in Your Code

After you have defined your structure, you can use its identifier as a variable type, just as you would an int or a long type. Supply the identifier of the structure, followed by some whitespace, followed by the identifier of the structure variable:

Point MyPoint;

Cross-Reference Identifiers can be found in Chapter 3, "Working with Variables."

This statement declares a variable called MyPoint whose type is the Point structure. You can use this variable just as you would any variable, including within expressions and as a parameter to a method.

Accessing the individual members of the structure is as easy as writing the name of the structure variable identifier, a period, and then the structure member. Listing 7-1 shows how a structure may be used in code.

Listing 7-1: Accessing Structure Members class Listing7 1

struct Point {

public int X; public int Y;

public static void Main() {

Point MyPoint;

System.Console.WriteLine(MyPoint.X); System.Console.WriteLine(MyPoint.Y);

The output for the example show would be as follows:

### 100 200

You can assign one structure variable to another, as long as the structures are of the same type. When you assign one structure variable to another, C# sets the values of the structure variable shown before the equal sign to the values of the corresponding values found in the structure shown after the equal sign, as shown in Listing 7-2.

Listing 7-2: Assigning One Structure Variable to Another

Listing 7-2: Assigning One Structure Variable to Another class Listing7 2 {

struct Point {

public int X; public int Y;

class Listing7 2 {

struct Point {

public int X; public int Y;

public static void Main() {

Point MyFirstPoint; Point MySecondPoint;

MyFirstPoint.X = 100; MyFirstPoint.Y = 100; MySecondPoint.X = 200; MySecondPoint.Y = 200;

System.Console.WriteLine(MyFirstPoint.X); System.Console.WriteLine(MyFirstPoint.Y);

MyFirstPoint = MySecondPoint;

System.Console.WriteLine(MyFirstPoint.X); System.Console.WriteLine(MyFirstPoint.Y);

The preceding code sets the MyFirstPoint members to 100 and the MySecondPoint members to 200. The MyFirstPoint values are written to the console, and then the values in the MyFirstPoint variable is copied into the values found in the MySecondPoint variable. After the assignment, the MyFirstPoint values are again written to the console. When this code is compiled and executed, the output should be that of Figure 7-1.

vCfceptftr 7-Liix i*i7?M*in".D*(W-ai?LI>tT tag? 7 .»>«

I'vCluipfcPr tay?-3T\bln\Diilbijj|i}

Figure 7-1: Assigning one structure to another

Any values in a structure are overwritten in an assignment with the values from the structure variable listed after the equal sign.

0 0