views:

285

answers:

7

The code below shows a sample that I've used recently to explain the different behaviour of structs and classes to someone brand new to development. Is there a better way of doing so? (Yes - the code uses public fields - that's purely for brevity)

namespace StructsVsClasses
{
    class Program
    {
        static void Main(string[] args)
        {
            sampleStruct struct1 = new sampleStruct();
            struct1.IntegerValue = 3;
            Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);

            sampleStruct struct2 = struct1;
            Console.WriteLine();
            Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
            Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);
            struct1.IntegerValue = 5;
            Console.WriteLine();
            Console.WriteLine("struct1.IntegerValue: {0}", struct1.IntegerValue);
            Console.WriteLine("struct2.IntegerValue: {0}", struct2.IntegerValue);

            sampleClass class1 = new sampleClass();
            class1.IntegerValue = 3;
            Console.WriteLine();
            Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);

            sampleClass class2 = class1;
            Console.WriteLine();
            Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
            Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);
            class1.IntegerValue = 5;
            Console.WriteLine();
            Console.WriteLine("class1.IntegerValue: {0}", class1.IntegerValue);
            Console.WriteLine("class2.IntegerValue: {0}", class2.IntegerValue);

            Console.ReadKey();
        }
    }

    struct sampleStruct
    {
        public int IntegerValue;
    }

    class sampleClass
    {
        public int IntegerValue;
    }
}
+1  A: 

I guess it's OK to show the difference as far as value/reference types are concerned this way. It might be a little bit cleaner to use methods for the console output, though.

As you said your "someone" was new to development this might not be too important, but there is a nice list of further differences between classes and structs in C# here:

C# struct/classes differences

Grimtron
+4  A: 

Well, your explanation isn't an explanation at all, it's an observation of behavior, which is different.

If you want an explanation of what the difference is, then you need a piece of text explaining it. And the behavior explained can be ed with the code.

The page linked to by Grimtron is good for detailing all the individual differences between a class and a struct, and pieces of it would serve as a overview explanation, in particular read the following items:

  • Exists on stack or heap?
  • Inheritance differences?

But I wouldn't link to that page as an explanation for what the differences are. It's like trying to describe what a car is, and just listing up all the parts that make up a car. You still need to understand the big picture to understand what a car is, and such a list would not be able to give you that.

In my mind, an explanation is something that tells you how something works, and then all the details follow naturally from that.

For instance, if you understand the basic underlying principles behind a value type vs. a reference type, a lot of the details on that page makes sense, if you think about it.

For instance, a value type (struct) is allocated where it is declared, inline, so to speak. It takes up stack space, or makes a class bigger in memory. A reference type, however, is a pointer, which has a fixed size, to somewhere else in memory where the actual object is stored.

With the above explanation, the following details makes sense:

  • A struct variable cannot be null (ie. it always takes up the necessary space)
  • An object reference can be null (ie. the pointer can point to nothing)
  • A struct does not add pressure to garbage collection (garbage collection works with the heap, which is where objects live in that somewhere else space)
  • Always have a default constructor. Since you can declare any value-type variable (which is basically a kind of struct), without giving it a value, there must be some underlying magic that clears up that space (remember I said it took up space anyhow)

Other things, like all the things related to inheritance, needs their own part in the explanation.

And so on...

Lasse V. Karlsen
A: 
  1. I don't see what you're trying to show with your sample.

  2. The way I explain it to people is "A structure holds stuff. A class does something with it".

Brad Bruce
That's the typical usage, but there's nothing stopping you from making a class that holds stuff and a struct that does something with it.
Lasse V. Karlsen
A: 

lassevk,

Thanks for that (semantic nitpicking aside :=) - however, maybe I wasn't as clear as I could be, I was trying to show rather than tell as to someone new to development, a block of prose like that means about as much as the average bit of Star Trek-esque technobabble.

The page Grimtron linked to, and your text will certainly be useful once my newbie is more familiar/comfortable with .net and programming in general, I'm sure!

Rob
+1  A: 

The difference might be easier to understand when the struct/class is a member of another class.

Example with class:

class PointClass {
  int double X;
  int double Y;
}

class Circle {
  PointClass Center = new PointClass() { X = 0, Y = 0; }
}

static void Main() {
  Circle c = new Circle();
  Console.WriteLine(c.Center.X);
  c.Center.X = 42;
  Console.WriteLine(c.Center.X);
}

Output:

0
42

Example with struct:

struct Point {
  int double X;
  int double Y;
}

class Circle {
  PointStruct Center = new PointStruct() { X = 0, Y = 0; }
}

static void Main() {
  Circle c = new Circle();
  Console.WriteLine(c.Center.X);
  c.Center.X = 42;
  Console.WriteLine(c.Center.X);
}

Output:

0
0
Hallgrim
This is a nice rosetta stone for an extremely simple example but really doesn't do much to contrast the two. This shows syntax but doesn't explain why you would (or must) use one or the other.
Michael Haren
A: 

A structure is a limp, lifeless arrangement of data. Flaccid and passive.

A class explodes into action in the blink of a constructor. Bursting with vitality a class is the superhero of the modern [programming] world.

Ed Guiness
A: 

The very basic difference is that Structure is Value Types and Class is Reference Type

Prashant
Prashant - that doesn't mean *anything* to someone who's new to development - that's the thrust of this question =)
Rob