Structs Are Value Types

Structs Are Value Types

 

Although structs are value types, you can often treat them syntactically in the same way as classes.

For example, with the definition of the Dimensions class in the previous section, you could write:

 

Dimensions point = new Dimensions();

point.Length = 3;

point.Width = 6;

 

Note that because structs are value types, the new operator does not work in the same way as it does for

classes and other reference types. Instead of allocating memory on the heap, the new operator simply

calls the appropriate constructor, according to the parameters passed to it, initializing all fields.

 Indeed, for structs it is perfectly legal to write:

 

Dimensions point;

point.Length = 3;

point.Width = 6;

If Dimensions was a class, this would produce a compilation error, because point would contain an

uninitialized reference — an address that points nowhere, so you could not start setting values to its

fields. For a struct, however, the variable declaration actually allocates space on the stack for the entire

struct, so it ' s ready to assign values to. Note, however, that the following code would cause a

compilation error, with the compiler complaining that you are using an uninitialized variable:

 

Dimensions point;

Double D = point.Length;

 

Structs follow the same rules as any other data type — everything must be initialized before use. A struct

is considered fully initialized either when the new operator has been called against it, or when values

have been individually assigned to all its fields. And of course, a struct defined as a member field of a

class is initialized by being zeroed - out automatically when the containing object is initialized.

 

The fact that structs are value types will affect performance, though depending on how you use your

struct, this can be good or bad.

 

On the positive side, allocating memory for structs is very fast because

this takes place inline or on the stack. The same goes for removing structs when they go out of scope.

 

On the negative side, whenever you pass a struct as a parameter or assign a struct to another struct (as in

A=B , where A and B are structs), the full contents of the struct are copied, whereas for a class only the

reference is copied. This will result in a performance loss that depends on the size of the struct,

emphasizing the fact that structs are really intended for small data structures.

 Note, however, that when passing a struct as a parameter to a method, you can avoid this performance loss by passing it

as a ref parameter — in this case, only the address in memory of the struct will be passed in, which is just as fast

as passing in a class. If you do this, though, be aware that it means the called method can in principle

change the value of the struct.

 

 

Next Recommended Reading Get am/pm from datetime in sql query