1. Home
  2. Computing & Technology
  3. C / C++ / C#

C# Tutorial - About Value Types and Reference Types

By David Bolton, About.com

3 of 10

More About Structs

Unlike C++, a default constructor is supplied even when you write your own constructor but you aren't forced to call it. The compiler will complain though if you try to use a variable that it knows has not been initialized.
struct_test t= new struct_test() ; // calls the default constructor
struct_test t2= new struct_test(8,7) ; // calls the constructor I wrote
struct_test t3; // Leaves the object uninitialized
These 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.
t3.a = 8; // compiler ok
int b= t3.b; // error - accessing uninitialized variable
This line
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.

Download Example 2

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

  1. Class 3.6 seconds.
  2. Struct 1.4 seconds.
So if you can use a struct rather than a class, do so. It will make a bit of a difference.

On the next page : Working with Reference Types

Explore C / C++ / C#
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. More About Structs

©2009 About.com, a part of The New York Times Company.

All rights reserved.