Skip to content

What Are Structs?

Structs are programmer-defined data types, similar to classes. They have data members and function
members. Although structs are similar to classes, there are a number of important differences. The most
important ones are the following:
• Classes are reference types, and structs are value types.
• Structs are implicitly sealed, which means they cannot be derived from.
The syntax for declaring a struct is similar to that of declaring a class.

				
					struct StructName
{
    MemberDeclarations
}
				
			

For example, the following code declares a struct named Point. It has two public fields, named X and Y.
In Main, three variables of struct type Point are declared, and their values are assigned and printed out.

				
					struct Point
{
    public int X;
    public int Y;
}
class Program
{
static void Main()
    {
        Point first, second, third;
        first.X = 10; first.Y = 10;
        second.X = 20; second.Y = 20;
        third.X = first.X + second.X;
        third.Y = first.Y + second.Y;
        Console.WriteLine($"first: { first.X }, { first.Y }");
        Console.WriteLine($"second: { second.X }, { second.Y }");
        Console.WriteLine($"third: { third.X }, { third.Y }");
    }
}
				
			

Structs Are Value Types
As with all value types, a variable of a struct type contains its own data. Consequently,
• A variable of a struct type cannot be null.
• Two struct variables cannot refer to the same object.
For example, the following code declares a class called CSimple, a struct called Simple, and a variable of
each. Figure 11-1 shows how the two would be arranged in memory.

Assigning to a Struct

Assigning one struct to another copies the values from one to the other. This is quite different from copying from a class variable, where only the reference is copied.

Below figure shows the difference between the assignment of a class variable and a struct variable. Notice that after the class assignment, cs2 points at the same object in the heap as cs1. But after the struct assignment, the values of ss2’s members are copies of those in ss1.

				
					class CSimple
{ 
    public int X; public int ; 
}

struct Simple
{ 
    public int X; public int ; 
}

class Program
{
    static void Main()
    {
        CSimple cs1 = new CSimple(), cs2 = null; // Class instances
        Simple ss1 = new Simple(), ss2 = new Simple(); // Struct instances
        cs1.X = ss1.X = 5; // Assign 5 to ss1.X and cs1.X.
        cs1.Y = ss1.Y = 10; // Assign 10 to ss1.Y and cs1.Y.
        cs2 = cs1; // Assign class instance.
        ss2 = ss1; // Assign struct instance.
    }
}
				
			

Leave a Reply

Your email address will not be published.