views:

152

answers:

8

Whenever I tried to search about differences between classes and structs in C# or .net, I ended up with the conceptual overview of the two things like value type or the reference type, where the variables are allocated etc. But I need some practical differences. I have found some like different behavior of assignment operator, having constructors etc. Can anybody provide some more practical differences which will be directly useful while coding? Like the things works with one but not with other or same operation showing different behavior. And some common mistakes regarding these two.

Also please suggest where to consider using a struct instead of a class. And where the structs should not be used.

Edit: Do I have to call the constructor explicitly or just declaring a struct type variable will suffice?(Should I make it a new question?)

A: 

Here's an interesting link: http://www.jaggersoft.com/pubs/StructsVsClasses.htm

For the most part though, there isn't much of a compelling reason to use structs when classes offer far more to the developer.

Tejs
Good reference material.
Amry
-1: While the reference may be good, some explanations and code examples would be preferable. If that link goes away then this answer is meaningless.
dboarman
-1 for the blanket statement that makes it sound like structs are completely useless and should never be used.
Timwi
+1  A: 

Structs in a container can only be modified if the container is a built-in array:

struct Point { public int x, y; void Move(int dx, int dy) { x += dx; y += dy; } }
...
Point[] points = getPointsArray();
points[0].Move(10, 0) = 10;
// points[0].x is now 10 higher.
List<Point> points = getPointsList();
points[0].Move(10, 0);
// No error, but points[0].x hasn't changed.

For this reason, I strongly favour immutable structs:

Point Move(int dx, int dy) { return new Point(x + dx, y + dy); }
...
points[0] = points[0].Move(10, 0); // Always works.

General observation: classes are usually better. Structs excel when you want to hold small, conceptually atomic data structures such as Point, Complex (number), Rational, etc.

Marcelo Cantos
This is true, but the reason for this might be hard to perceive at first sight, and is not actually related to arrays. Since structs are value types, indexing the list returns a copy of the actual struct, and changing it (using the `Move` method) does not change the original value. Same behaviour would be perceived if that struct was in a public property of a different class. Furthermore, `points[0] = points[0].Move(10, 0);` would "work" with a mutable struct also.
Groo
@Groo: It _is_ related to arrays in the sense that only arrays support mutation of struct elements. They are _privileged_, in a sense, which is something I dislike in the design of a language (C++, for all its warts and bedsores, doesn't exhibit this flaw with its containers). Certainly the alternate `Move` semantics would work with a mutable struct, but then a mutable struct typically wouldn't implement `Move` that way.
Marcelo Cantos
+1  A: 

structs, as they are value types, are copied on assignment; if you create your own struct, you should make it immutable, see Why are mutable structs evil?

gammelgul
A: 

Where they are allocated (heap vs. stack) is not something you really care about while you use them (not that you should disregard this - you should by all means study the differences and understand them).

But the most important practical difference you will come across the first time you decide to replace your class with a struct, is that structs are passed by value, while class instances are passed by reference.

This means that when you pass a struct to a method, a copy of its properties is created (a shallow copy) and your method actually gets a different copy than the one you had outside the method. When you pass an instance of a class, only a reference to the same place in memory is passed to the method, and your method is then dealing with exactly the same data.

For example, if you have a struct named MyStruct, and a class named MyClass, and you pass them to this method:

 void DoSomething(MyStruct str, MyClass cls)
 {
      // this will change the copy of str, but changes
      // will not be made to the outside struct
      str.Something = str.Something + 1;

      // this will change the actual class outside
      // the method, because cls points to the
      // same instance in memory
      cls.Something = cls.Something + 1;
 }

when the method ends, your class' property will be incremented, but your struct's property will remain unchanged, because str variable inside the DoSomething method does not point to the same place in memory.

Groo
A: 

The singularly important practical difference is that structs are value types, whereas classes are reference types. That has a few implications.

First of all, structs are copied on assignment. These two code blocks will have a different result (please note, normally you should neither use public fields nor mutable structs, I'm doing this for demonstration purposes only):

struct X
{
    public int ID;
    public string Name;
}

X x1 = new X { ID = 1, Name = "Foo" };
X x2 = x1;
x2.Name = "Bar";
Console.WriteLine(x1.Name);    // Will print "Foo"

class Y
{
    public int ID;
    public string Name;
}
Y y1 = new Y { ID = 2, Name = "Bar" };
Y y2 = y1;
y2.Name = "Baz";
Console.WriteLine(y1.Name);    // Will print "Baz"

X and Y are exactly the same, except that X is a struct. The results of this are different because every time we assign an X, a copy is made, and if we change the copy then we aren't changing the original. On the other hand, when we assign the contents of y1 to y2, all we've done is copied a reference; both y1 and y2 refer to physically the same object in memory.

The second consequence of structs being value types is generic constraints. If you want to pass in value types, the name of the constraint is literally "struct" or "class":

public class MyGeneric<T>
    where T : struct
{ ... }

The above will let you create a MyGeneric<int> or MyGeneric<X>, but not a MyGeneric<Y>. On the other hand, if we change it to where T : struct, we're no longer allowed to create either of the first two, but MyGeneric<Y> is okay.

Last but not least, you need to use structs when writing interop, because with structs you're able to guarantee a specific arrangement in memory.

Aaronaught
+1  A: 

Sometimes you don't want what you're passing to be mutable, and since a mutable struct may just be pure evil, I'd steer clear of ever creating one :) Here's an example a situation:

class Version:

class AccountInfo {
   public string OwnerName { get; set; }
   public string AccountNumber { get; set; }
}

struct Version:

struct AccountInfo {
   public string OwnerName;
   public string AccountNumber;
}

Now picture you called a method like this:

public bool TransferMoney(AccountInfo from, AccountInfo to, decimal amount)
{
   if(!IsAuthorized(from)) return false;
   //Transfer money
}

A struct is a Value type, meaning a copy gets passed into the method. The class version means a reference gets passed into the method, you wouldn't want for example the account number to be changeable after the authorization passed, you want nothing to be changed in an operation like this...you want an immutable value type. There's another question here asking why mutable structs are evil...any operation where you wouldn't want anything affected by the reference object changing, would be a practical place where a struct may fit better.

The example above may be somewhat silly, but the point is any sensitive operation where the passed in data shouldn't change in another thread or by any means really would be a place you look at passing by value.

Nick Craver
Properties don't work within struct?
Gulshan
@Gulshan - Yes they do work, just old habit writing them like above. I prefer a `struct` to me immediately recognizable inside and out when coding.
Nick Craver
A: 

The link Tejs provided (http://www.jaggersoft.com/pubs/StructsVsClasses.htm) is a good explanation (although it is a bit out of date, particularly on the explanation of events).

The most import practical difference is that a struct is a value type, meaning it is passed by value rather than by reference. What this really means is that when a struct is passed as an argument, it is actually passed by copy. As a result, operations on one instance of a struct do not affect other instances.

Consider the following code:

struct NumberStruct
{
   public int Value;
}

class NumberClass
{
   public int Value = 0;
}

class Test
{
   static void Main() 
   {
      NumberStruct ns1 = new NumberStruct();
      NumberStruct ns2 = ns1;
      ns2.Value = 42;

      NumberClass nc1 = new NumberClass();
      NumberClass nc2 = nc1;
      nc2.Value = 42;

      Console.WriteLine("Struct: {0}, {1}", ns1.Value, ns2.Value);
      Console.WriteLine("Class: {0}, {1}", nc1.Value, nc2.Value);
   }
}

Because both ns1 and ns2 are of the NumberStruct value type, they each have their own storage location, so the assignment of ns2.Number does not affect the value of ns1.Number. However, because nc1 and nc2 are both reference types, the assignment of nc2.Number does affect the value of nc1.Number because they both contain the same reference.

[Disclaimer: The above code and text taken from Sams Teach Yourself Visual C# 2010 in 24 Hours]

Also, as others have already pointed out, structs should always be immutable. (Yes, in this example the struct is mutable but it was to illustrate the point.) Part of that means that structs should not contain public fields.

Since structs are value types, you cannot inherit from a struct. You also cannot derive a struct from a base class. (A struct can implement interfaces, however.)

A struct is also not allowed to have an explicitly declared public default (parameterless) contstructor. Any additional constructors you declare must completely initialize all of the struct fields. Structs also cannot have an explicitly declared destructor.

Since structs are value types, they shouldn't implement IDisposable and shouldn't contain unmanaged code.

Scott Dorman
+3  A: 

OK, here are a few specific, practical differences:

  • A variable can be null if it’s a class, but is never null if it’s a struct.

  • default(T) is null for a class, but for a struct actually constructs a value (consisting of lots of binary zeros).

  • A struct can be made nullable by using Nullable<T> or T?. A class cannot be used for the T in Nullable<T> or T?.

  • A struct always has a public default constructor (a constructor with zero parameters). The programmer cannot override this constructor with a custom implementation — it is basically “set in stone”. A class allows the programmer to have no default constructor (or a private one).

  • The fields in a class can have default values declared on them. In a struct they can’t.

  • A class can inherit from another class, but a struct cannot be declared to derive from anything (it implicitly derives from System.ValueType).

  • It makes sense to use a class in object.ReferenceEquals(), but using a struct variable will always yield false.

  • It makes sense to use a class in a lock() statement, but using a struct variable will cause very subtle failure. The code will not be locked.

  • On a 32-bit system, you can theoretically allocate an array of up to 536,870,912 instances of a class, but for a struct you need to take the size of the struct into account.

Timwi