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

C# Tutorial - About Value Types and Reference Types

By , About.com Guide

5 of 10

Reference versus Value- Which should I use?

Value types hold data, but reference types i.e. classes are meant to control how applications behave. The use of the two should be distinguished early on. If you use structs and then later change them to classes, you may introduce some nasty bugs. Why? Because if you pass a struct by value as a function parameter then a copy of it is made in the function, and that copy used. The original struct is left unchanged unless the keyword ref is added to the call and the definition.
public struct t1
{
  public int Total;
}

public static int AddFive( t1 x)
{
  x.Total += 5;
  return x.Total;
}
In this example (Download Example 4_1) x is a struct and is passed into AddFive. If x.Total was 0 upon entry then AddFive() will return 5 but x.Total will still be 0. Now change t1 to a class and because it is a reference type, x.Total will be 5 when AddFive() exits.

Boxing

Originally from Java, the concept of boxing is about storing a value type variable in a reference variable.
int i = 99;
object t=(object)i;
Console.WriteLine("Value of t ={0}",(int)t) ;
Console.WriteLine("Value of t ={0}",t) ;
Console.ReadKey() ;
This wraps the variable i in an object t i.e. inside a box. Remember all types ultimately derive from System.object.
Note - Boxing is a relatively slow process. According to Microsoft it takes 20 times as long as an assignment. This is because an object has to be created, then the valuetype variable copied into it. The opposite is unboxing, which is about four times as slow as assignment.

When would You Use Boxing?

The answer is you wouldn't if you can help it. If C# 1.0 and 1.1, it made possible null value value types (by boxing them as reference types) but with the nullable types in .NET 2.0 that is no longer needed.

On the next page Static and Instance Classes

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

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

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

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C# / C Sharp
  5. Learn C Sharp
  6. Reference versus Value- Which should I use?

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

All rights reserved.