c# when to use Structure instead of class in real life application

T.Zacks 3,996 Reputation points
2022-09-12T17:37:04.187+00:00

i read this page https://learn.microsoft.com/en-us/dotnet/standard/design-guidelines/choosing-between-class-and-struct?redirectedfrom=MSDN

but still like to gather list of points like when to use Structure instead of class in real life application.

please share points. thanks

Developer technologies C#
{count} votes

2 answers

Sort by: Most helpful
  1. Michael Taylor 60,161 Reputation points
    2022-09-12T18:40:12.91+00:00

    The answer is pretty straightforward. Are you representing an entity in your business model? Use a class. Are you grouping a set of related values together that don't make any sense by themselves (e.g. coordinates, complex number) then use a struct. If you aren't sure then use a class.

    What really matters is reference vs value types. Classes are ref types in C# and structs are value types. The runtime enforces the ref vs value type rules. You can read about them in the documentation you're reading.

    Reference types (at least until you enable nullable reference types)

    • Can be null so you must code for that
    • Follow reference semantics for assignment (copy the reference so you can have multiple variables pointing to same object)
    • Follow reference semantics for equality (2 values are equal only if they refer to same object in memory)
    • Allocated in heap
    • Can fully customize construction

    Value types

    • Can never be null
    • Follow value semantics for assignment (copy value each time)
    • Follow value semantics for equality (2 values are equal if they values they store are equal)
    • Allocated on call stack
    • Should be small (generally less than 64 bytes)
    • Cannot have a default constructor

    Note that rules around equality can be altered in advanced situations but that is not normal.

    So, at the end of the day, if you need to store data and functionality then use a class. If you just need to store data then use a struct. If you're not sure then use a class.

    0 comments No comments

  2. Bruce (SqlWork.com) 77,686 Reputation points Volunteer Moderator
    2022-09-12T19:49:40.023+00:00

    the importance of a struct is that it is a value type (like int, bool, double, etc). value types have some important properties:

    value types are allocated on the stack (unless static, then at compile time). thus they require no memory allocations and don't invoke a GC.
    value are copied on assignment or when passed to a method
    value types are boxed when stored as an object (this copies them to the heap)

    while some languages like swift and rust are optimized for stucts, C# isn't and prefers small stucts.

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.