Re: Value Types and Reference Types

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



Jon Slaughter <Jon_Slaughter@xxxxxxxxxxx> wrote:

<snip>

Whats the real difference? just optimization. Its easier to put things on
the stack than the heap(ok, maybe not really that much harder) and its
usually more efficient because of the cpu's cache and stuff.

In a sense what I'm trying to get at is that the struct is like a
lightweight version of a class.

No, you've completely missed the point of the distinction between value
types and reference types.

*Please* read
http://pobox.com/~skeet/csharp/references.html
and
http://pobox.com/~skeet/csharp/parameters.html
before making any more claims like this.

In particular, consider the following program:

using System;
using System.Text;

public class Test
{
static void Main()
{
StringBuilder builder = new StringBuilder();
StringBuilder otherBuilder = builder;
builder.Append("Hi");

Console.WriteLine(otherBuilder.ToString());
}
}

If your explanation was correct, it would make no difference to the
output (optimisation shouldn't affect output, right?) whether
StringBuilder is a value type or a reference type. The reality couldn't
be more different.

--
Jon Skeet - <skeet@xxxxxxxxx>
http://www.pobox.com/~skeet Blog: http://www.msmvps.com/jon.skeet
World class .NET training in the UK: http://iterativetraining.co.uk
.