Information Technology Reference
In-Depth Information
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.
Figure 12-2 shows the difference between the assignment of a class variable and a struct
variable. Notice that after the class assignment, cs2 is pointing at the same object in the heap as
cs1 . But after the struct assignment, the values of ss2 's members are the same as those of ss1 .
class CSimple
{ public int x; public int y; }
struct Simple
{ public int x; public int y; }
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
Figure 12-2. Assigning a class variable and a struct variable
Search WWH ::




Custom Search