Home   Cover Cover Cover Cover
 

Classes and Structs

Question: In which situations would you use classes and in which structs?

Answer: Classes are reference types, structs are value types. Objects of classes are allocated on the heap, objects of structs are stored on the method stack (or are embedded in other objects).

  • Structs are more lightweigth than classes, because they do not burden the garbage collector. They are mainly used for simple data objects without methods, which are often just used temporarily in a method or as a part of some other object. Structs cannot be extended by inheritance and cannot be connected via pointers. Thus they are rarely used in complex data structures.


  • Classes are often used for complex objects with methods, as well as for dynamic data structures such as lists, trees or graphs. Most objects of classes are not local to a method but are part of a global data structure on the heap. Classes can inherit from other classes and can make use of dynamic binding of methods.