views:

8415

answers:

12

I'm looking for a clear, concise and accurate answer.

Ideally as the actual answer, although links to good explanations welcome.

+2  A: 

Well, for starters, a struct is passed by value rather than by reference. Structs are good for relatively simple data structures, while classes have a lot more flexibility from an architectural point of view via polymorphism and inheritance.

Others can probably give you more detail than I, but I use structs when the structure that I am going for is simple.

Ed Swangren
+3  A: 

I think this article "Type Fundamentals" by Jeffrey Richter is a very good place to start.

John
+1  A: 

In .Net the struct and class declarations differentiate between reference types and value types.

When you pass round a reference type there is only one actually stored. All the code that accesses the instance is accessing the same one.

When you pass round a value type each one is a copy. All the code is working on it's own copy.

This can be shown with an example:

void ChangeInt( int input ) { 
   input = 25;
}

...

int testStruct = 15; //value type

ChangeInt( testStruct );

//value of testInt is still 15 - the method changed a copy

For a class this would be different

class MyClass {
    string MyProperty { get; set; }
}

void ChangeMyClass ( MyClass input ) { 
   input.MyProperty = "new value";
}

...

MyClass testClass = new MyClass { MyProperty = "initial value" }; //ref type

ChangeMyClass ( testClass );

//value of testClass.MyProperty is now "new value" 
// - the method changed the instance passed.

Classes can be nothing - the reference can point to a null.

Structs are the actual value - they can be empty but never null. For this reason structs always have a default constructor with no parameters - they need a 'starting value'.

Keith
AR
Not a clue - this was posted quite early in the beta when we were all still just figuring out the rules.
Keith
A: 

Assuming it's similar to c++, a struct is a simple data structure that is used to contain several variables.

A class is a data structure that has defined operations (methods) and has protected variables for encapsulation.

DShook
+7  A: 

Instances of classes are stored on the managed heap. All variables 'containing' an instance are simply a reference to the instance on the heap. Passing an object to a method results in a copy of the reference being passed, not the object itself.

Structures (technically, value types) are stored wherever they are used, much like a primitive type. The contents may be copied by the runtime at any time and without invoking a customised copy-constructor. Passing a value type to a method involves copying the entire value, again without invoking any customisable code.

The distinction is made better by the C++/CLI names: "ref class" is a class as described first, "value class" is a class as described second. The keywords "class" and "struct" as used by C# are simply something that must be learned.

Zooba
+2  A: 

Structs are the actual value - they can be empty but never null

This is true, however also note that as of .NET 2 structs support a Nullable version and C# supplies some syntactic sugar to make it easier to use.

int? value = null;
value  = 1;
dpp
Be aware that this is only syntactic sugar which reads 'Nullable<int> value = null;'
Erik van Brakel
A: 

Yeah @dp, I thought that might be a little off topic, but it makes sense to mention that here.

You can also check with ??, so:

int? i = SomeFunctionThatMightGetAnInt();

//if i is null write 0, otherwise write i
Console.Write( i ?? 0 );
Keith
+59  A: 

In .NET, there are two categories of types, reference types and value types.

Structs are value types and classes are reference types.

The general different is that a reference type lives on the heap, and a value type lives inline, that is, wherever it is your variable or field is defined.

A variable containing a value type contains the entire value type value. For a struct, that means that the variable contains the entire struct, with all its fields.

A variable containing a reference type contains a pointer, or a reference to somewhere else in memory where the actual value resides.

This has one benefit, to begin with:

  • value types always contains a value
  • reference types can contain a null-reference, meaning that they don't refer to anything at all at the moment

Internally, reference types are implemented as pointers, and knowing that, and knowing how variable assignment works, there are other behavioral patterns:

  • copying the contents of a value type variable into another variable, copies the entire contents into the new variable, making the two distinct. In other words, after the copy, changes to one won't affect the other
  • copying the contents of a reference type variable into another variable, copies the reference, which means you now have two references to the same somewhere else storage of the actual data. In other words, after the copy, changing the data in one reference will appear to affect the other as well, but only because you're really just looking at the same data both places

When you declare variables or fields, here's how the two types differ:

  • variable: value type lives on the stack, reference type lives on the stack as a pointer to somewhere in heap memory where the actual memory lives
  • class/struct-field: value type lives inside the class, reference type lives inside the class as a pointer to somewhere in heap memory where the actual memory lives.
Lasse V. Karlsen
This has to be about the clearest and most helpful answer to this question I have seen. (and I've seen a lot of attempted answers)
StarPacker
+2  A: 

A short summary of each, with differences highlighted in italics:

Classes Only:

  • Can support inheritance
  • Are reference types and so are always allocated on the heap

Structs Only:

  • Cannot support inheritance
  • Are value types and so are allocated on the stack, unless boxed

Both Classes and Structs:

  • Are compound data types typically used to contain a few variables that have some logical relationship
  • Can contain methods and events
  • Can support interfaces
Thomas Bratt
There are some parts of this answer that are not quite right. Classes do not always go on the heap, and structs do not always go on the stack. Current exceptions include struct fields on a class, captured variables in anonymous methods and lambda expressions, iterator blocks, and the already mentioned boxed values. But stack vs heap allocation is a implementation detail and may be subject to change. [Eric lippart discusses this here](http://blogs.msdn.com/b/ericlippert/archive/2009/04/27/the-stack-is-an-implementation-detail.aspx). I've downvoted, but will happily remove it if you update.
Simon P Stevens
+3  A: 

The question is pretty much answered at this point.

It might be of interest a quick and dirty guide to choosing between struct and class in every-day coding.

JohnIdol
A: 

Remember the answer, as 99% of interviews I've had use it! Here's two more explanations to add the list:

Chris S
Yeah, it's one I always ask.
Keith
That would be *understand the answer*, not *remember it*, right?
Groo
No, remember some text book answer that makes it sound like you work for the CLR team instead of understanding that 90% of the time you won't care http://blogs.msdn.com/ericlippert/archive/2009/05/04/the-stack-is-an-implementation-detail-part-two.aspx
Chris S
A: 

Structure vs Class Structure is value type so stored in stack,but class is reference type stored in heap. Structure doesn't support inheritance,polymorphism but,class supports both. By default all the struct members are public but class members are by default private in nature. As structure is value type,we can't assign null to struct object,but it is not the case in class.

Swagatika dhal