paperlined.org
dev > programming_languages > csharp
document updated 16 years ago, on Mar 7, 2008
In C#, classes and structs appear on the surface to be very similar (they can both have
constructors, member functions, and properties).  However, there is one important difference:
structs are value-types, and classes are reference-types.  For people more familiar with
Java/Python/etc, this has several surprising implications:

- struct variables can't be assigned `null`, while class variables can be

- structs are pass-by-value, classes are pass-by-reference
        (this may be very startling for people coming from Java/Python, since you may think you're
        modifying the original struct, but may instead be modifying a copy of the struct)

        (for C people though, this may actually be quite obvious.  However, since C# is much closer
        to Java/Python in most other respects, it may still be somewhat unexpected that C# takes
        this one detail from C)
        

And the following benefits:

- as local variables:  structs get allocated on the stack, classes get allocated on the heap

- an array of structs is a single contiguous block of memory;  an array of classes is an array of
  references, initially assigned null, and later pointing to non-adjacent blocks of memory




(conclusion: C# *really* is a hybrid between Java and C)




See also:
    http://www.jaggersoft.com/pubs/StructsVsClasses.htm