C# struct/class Differences
struct Direct
{
//...
}
class InDirect
{
//...
}
Events are locked?
Exist on stack or heap?
Can cause garbage collection?
Meaning of this?
Always has a default constructor?
Default construction triggers static construction?
Can be null?
Use with the as Operator?
Can be locked?
Can have a destructor?
Default fIEld layout?
Can be a volatile fIEld?
Can have synchronized methods?
Can be pointed to?
Can be stackalloc’d?
Can be sizeof’d?
How to initialize fIElds?
Inheritance differences?
Equals behavior
Events are locked?
Events declared in a class have their += and -= access automatically locked via a lock(this) to make them thread safe (static events are locked on the typeof the class). Events declared in a struct do not have their += and -= Access automatically locked. A lock(this) for a struct would not work since you can only lock on a reference type expression.
Exist on stack or heap?
Value type local instances are allocated on the stack. Reference type local instances are allocated on the heap.
Can cause garbage collection?
Creating a struct instance cannot cause a garbage collection (unless the constructor directly or indirectly creates a reference type instance) whereas creating a reference type instance can cause garbage collection.
Meaning of this?
In a class, this is classifIEd as a value, and thus cannot appear on the left hand side of an assignment, or be used as a ref/out parameter. For example:
class Indirect
{
//...
public void Method(Indirect that)
{
RefParameter(ref this); // compile-time error
OutParameter(out this); // compile-time error
this = that; // compile-time error
}
//...
}
In a struct, this is classifIEd as an out parameter in a constructor and as a ref parameter in all other function members. Thus it is possible to modify the entire structure by assigning to this or passing this as a ref/out parameter. For example:
struct Direct
{
//...
public void Reassign(Direct that)
{
RefParameter(ref this); // compiles ok
OutParameter(out this); // compiles ok
this = that; // compiles ok
}
//...
}
Furthermore, you can reassign a whole struct even when the struct contains readonly fIElds!
struct Direct
{
public Direct(int value)
{
FIEld = value;
}
public void Reassign(Direct that)
{
RefParameter(ref this); // compiles ok
OutParameter(out this); // compiles ok
this = that; // compiles ok
}
public readonly int FIEld;
}
class Show
{
static void Main()
{
Direct s = new Direct(42);
Console.WriteLine(s.FIEld); // writes 42
s.Reassign(new Direct(24));
Console.WriteLine(s.FIEld); // writes 24
}
}
Note however that when you call a method on a readonly value-type field, the method call is made on a copy of the fIEld.
struct Direct
{
// as above
}
class Caller
{
public void Method()
{
Console.WriteLine(d.FIEld); // writes 42
d.Reassign(new Direct(24));
Console.WriteLine(d.FIEld); // writes 42!
}
private readonly Direct d = new Direct(42);
}
class Show
{
static void Main()
{
Caller c = new Caller();
c.Method();
}
}
Always have a default constructor?
A struct always has a built-in public default constructor.
class DefaultConstructor
{
static void Eg()
{
Direct yes = new Direct(); // always compiles ok
InDirect maybe = new InDirect(); // compiles if c’tor exists and is Accessible
//...
}
}
This means that a struct is always instantiable whereas a class might not be since all its constructors could be private.
class NonInstantiable
{
private NonInstantiable() // ok
{
}
}
struct Direct
{
private Direct() // compile-time error
{
}
}
Default construction triggers static constructor?
A structs static constructor is not triggered by calling the structs default constructor. It is for a class.
struct Direct
{
static Direct()
{
Console.WriteLine("This is not written");
}
}
class NotTriggered
{
static void Main()
{
Direct local = new Direct();
}
}
Can be null?
A struct instance cannot be null.
class Nullness
{
static void Eg(Direct s, Indirect c)
{
if (s == null) ... // compile-time error
if (c == null) ... // compiles ok
}
}
Use with the as Operator?
A struct type cannot be the right hand side operand of the as Operator.
class Fragment
{
static void Eg(Direct s, Indirect c)
{
Direct no = s as Direct; // compile-time error
InDirect yes = c as InDirect; // compiles ok
//...
}
}
Can be locked?
A struct type expression cannot be the Operand of a lock statement.
class LockStatement
{
static void Eg(Direct s, InDirect c)
{
lock(s) { ... } // compile-time error
lock(c) { ... } // compiles ok
}
}
Can have a destructor?
A struct cannot have a destructor. A destructor is just an override of object.Finalize in disguise, and structs, being value types, are not subject to garabge collection.
struct Direct
{
~Direct() {} // compile-time error
}
class InDirect
{
~InDirect() {} // compiles ok
}
And the CIL for ~Indirect() looks like this:
.method family hidebysig virtual instance void
Finalize() cil managed
{
// ...
} // end of method Indirect::Finalize
Default fIEld layout?
The default [StructLayout] attribute (which lives in the System.Runtime.InteropServices namespace) for a struct is LayoutKind.Sequential whereas the default StructLayout for a class is LayoutKind.Auto. (And yes, despite its name you can tag a class with the StructLayout attribute.) In other Words the CIL for this:
public struct Direct
{
//...
}
looks like this:
.class public sequential ansi sealed beforefIEldinit Direct
extends [mscorlib]System.ValueType
{
//...
}
whereas the CIL for this:
public sealed class InDirect
{
//...
}
looks like this:
.class public auto ansi sealed beforefIEldinit Indirect
extends [mscorlib]System.Object
{
//...
}
Can be a volatile fIEld?
You can’t declare a user-defined struct type as a volatile field but you can declare a user-defined class type as a volatile fIEld.
class Bad
{
private volatile Direct fIEld; // compile-time error
}
class Good
{
private volatile Indirect fIEld; // compiles ok
}
Can have synchronized methods?
You can’t use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a struct type (if you call the method you get a runtime TypeLoadException) whereas you can use the [MethodImpl(MethodImplOptions.Synchronized)] attribute on methods of a class type.
using System.Runtime.CompilerServices;
class Indirect
{
[MethodImpl(MethodImplOptions.Synchronized)] // compiles and runs ok
public void Method()
{
//...
}
}
struct Direct
{
[MethodImpl(MethodImplOptions.Synchronized)] // compiles ok, runtime TypeLoadException
public void Method()
{
//...
}
}
Can be pointed to?
Clause 25.2 of the C# standard defines an unmanaged type as any type that isn’t a reference type and doesn’t contain reference-type fIElds at any level of nesting. That is, one of the following:
>Any simple value type (11.1.3, eg byte, int, long, double, bool, etc).
Any enum type.
Any pointer type.
Any user-defined struct-type that contains fIElds of unmanaged types only.
You can never take the address of a instance of a type that is not unmanaged (a fixed variable 25.3).
class Bad
{
static void Main()
{
Indirect variable = new Indirect();
unsafe
{
fixed(Indirect * ptr = &variable) // compile-time error
{
//...
}
}
}
}
If you want to fix an unmanaged instance you have to do so by fixing it through an unmanaged fIEld. For example:
class Indirect
{
public int fixHandle;
}
class Bad
{
static void Main()
{
Indirect variable = new Indirect();
unsafe
{
fixed(int * ptr = &variable.fixHandle) // compiles ok
; {
//...
}
}
}
}
In contrast, you can (nearly) always take the address of an unmanaged instance.
struct Direct
{
// no reference fIElds at any level of nesting
}
class SimpleCase
{
static void Main()
{
Direct variable = new Direct();
unsafe
{
Direct * ptr = &variable; // compiles ok
//...
}
}
}
However, you have to take the address inside a fixed statement if the variable is moveable (subject to relocation by the garbage collector, see 25.3 and example above). Also, you can never take the address of a volatile fIEld.
So, in summary, you can never create a pointer to a class type but you sometimes create a pointer to a struct type.
Can be stackalloc’d?
You can only use stackalloc on unmanaged types. Hence you can never use stackalloc on class types. For example:
class Indirect
{
//...
}
class Bad
{
static void Main()
{
unsafe
{
Indirect * array = stackalloc Indirect[42]; // compile-time error
//...
}
}
}
Where as you can use stackalloc on struct types that are unmanaged. For example:
struct Direct
{
// no reference fIElds at any level of nesting
}
class Good
{
static void Main()
{
unsafe
{
Direct * array = stackalloc Direct[42]; // compiles ok
//...
}
}
}
Can be sizeof’d?
You can only use sizeof on unmanaged types. Hence you can never use sizeof on class types. For example:
class Indirect
{
//...
}
class Bad
{
static void Main()
{
unsafe
{
int size = sizeof(Indirect); // compile-time error
//...
}
}
}
Where as you can use sizeof on struct types that are unmanaged. For example:
struct Direct
{
// no reference fIElds at any level of nesting
}
class Good
{
static void Main()
{
unsafe
{
int size = sizeof(Direct); // compiles ok
//...
}
}
}
How to initialize fIElds?
The fields of a class have a default initialization to zero/false/null. The fIElds of a struct have no default value.
struct Direct
{
public int FIEld;
}
class Indirect
{
public Indirect()
{
}
//...
public int FIEld;
}
class Defaults
{
static void Main()
{
Direct s;
Console.WriteLine(s.FIEld); // compile-time error
Indirect c = new Indirect();
Console.WriteLine(c.FIEld); // compiles ok
}
}
You can initialize fIElds in a class at their point of declaration. For example:
class Indirect
{
//...
private int fIEld = 42;
}
You can’t do this for fIElds in a struct. For example:
struct Direct
{
//...
private int fIEld = 42; // compile-time error
}
FIElds in a struct have to be initialized in a constructor. For example:
struct Direct
{
public Direct(int value)
{
fIEld = value;
}
//...
private int fIEld; // compiles ok
}
Also, the definite assignment rules of a struct are tracked on an individual field basis. This means you can bypass initialization and "assign" the fIElds of a struct one a time. For example:
struct Direct
{
public int X, Y;
}
class Example
{
static void Main()
{
Direct d;
d.X = 42;
Console.WriteLine(d.X); // compiles ok
Console.WriteLine(d.Y); // compile-time error
}
}
Inheritance differences?
a struct is implicitly sealed, a class isn’t.
a struct can’t be abstract, a class can.
a struct can’t call : base() in its constructor whereas a class with no explicit base class can.
a struct can’t extend another class, a class can.
a struct can’t declare protected members (eg fIElds, nested types) a class can.
a struct can’t declare abstract function members, an abstract class can.
a struct can’t declare virtual function members, a class can.
a struct can’t declare sealed function members, a class can.
a struct can’t declare override function members, a class can. The one exception to this rule is that a struct can override the virtual methods of System.Object, viz, Equals(), and GetHashCode(), and ToString().
Equals behavior?
classes inherit Object.Equals which implements identity equality whereas structs inherit ValueType.Equals which implements value equality.
using System.Diagnostics;
struct Direct
{
public Direct(int value)
{
fIEld = value;
}
private int fIEld;
}
class Indirect
{
public Indirect(int value)
{
fIEld = value;
}
private int fIEld;
}
class EqualsBehavior
{
static void Main()
{
Direct s1 = new Direct(42);
Direct s2 = new Direct(42);
Indirect c1 = new Indirect(42);
Indirect c2 = new Indirect(42);
bool structEquality = s1.Equals(s2);
bool classIdentity = !c1.Equals(c2);
Debug.Assert(structEquality);
Debug.Assert(classIdentity);
}
}
Overriding Equals for structs should be faster because it can avoid reflection and boxing.
struct Direct
{
public Direct(int value)
{
fIEld = value;
}
public override bool Equals(object other)
{
return other is Direct && Equals((Direct)other);
}
public static bool Operator==(Direct lhs, Direct rhs)
{
return lhs.Equals(rhs);
}
//...
private bool Equals(Direct other)
{
return field = other.fIEld;
}
private int fIEld;
}