Tuesday, April 3, 2007 9:00 AM by Michael Paladino
I've always read about structures and understood them to basically be dumbed-down classes but never had much more of an understanding than that. Going through the first chapter of my studying, I came across an explanation that makes sense to me. I'm sure there's much more to it than this, but structures are value types and not reference types. According to the book, "Value types are variables that contain their data directly instead of containing a reference to the data stored elsewhere in memory" as do instances of classes.
Consider the following code sample:
Dim p As Person = New Person("Michael", "Paladino", 28)
Dim p2 As Person = p
p2.firstName = "Leslie"
p2.age = 27
Console.WriteLine(p)
Console.WriteLine(p2)
In this code sample if Person is a Structure, creating p2 creates a new location in memory to store the data. Setting p2 equal to p actually copies the data from p to the new location in memory at p2. Therefore, changing the properties of p2 has no effect on p. Thus the output will be as follows:
Michael Paladino, Age:28
Leslie Paladino, Age:27
If Person is a Class, setting p2 equal to p causes p2 to point to the same location in memory as p. Therefore changing the properties on p2 also changes the properties of p, resulting in the following output:
Leslie Paladino, Age:27
Leslie Paladino, Age:27
Reference:
MCTS Self-Paced Training Kit (Exam 70-536): Microsoft .NET Framework 2.0-Application Development Foundation
Lesson 1: Using Value Types