struct_test t= new struct_test() ; // calls the default constructorThese are three ways of creating an instance of the object as shown above. If you attempt to read any field in t3, the compiler will complain. It's a compile error to read uninitialized variables. The built in default constructor initializes all fields to zero (0 for ints, 0.0 for floats,"" for strings, false for bool) etc.
struct_test t2= new struct_test(8,7) ; // calls the constructor I wrote
struct_test t3; // Leaves the object uninitialized
t3.a = 8; // compiler okThis line
int b= t3.b; // error - accessing uninitialized variable
Console.WriteLine("t2 = {0} ", t2) ;calls the t2.ToString() function which outputs 8 7.
Why Use Structs?
Because they are somewhat faster than classes at runtime, due to being directly accessed. Rather than use a full class for data structures, a struct is often more appropriate. Just how much faster though is a struct than a class? Example 2 gives an idea.This loops 100 million times creating an object from either a class or a struct depending on which of the two lines in the loop is commented out. There's a bit of code to copy the value out of the object and total it up, thus ensuring that the object isn't optimized out because it's not used. The execution times are
- Class 3.6 seconds.
- Struct 1.4 seconds.
On the next page : Working with Reference Types

