What is the difference between a class and a struct in C#?

1 Answers
Answered by suresh

Difference between a class and a struct in C#

Difference between a class and a struct in C#

In C#, both classes and structs are used to define custom types. Here are the key differences between them:

  • Memory Allocation: Classes are reference types, and they are allocated on the heap, while structs are value types and are allocated on the stack.
  • Inheritance: Classes support inheritance and can be used as base classes, while structs do not support inheritance.
  • Default Constructor: Classes have a default constructor, while structs do not have a default constructor and require all fields to be initialized.
  • Performance: Using structs can be more efficient in terms of memory and performance, especially for smaller data types, as they are stored inline and do not incur the overhead of heap allocation.
  • Usage: Classes are typically used for larger, more complex objects that require inheritance and reference semantics, while structs are commonly used for small, simple data structures.
Answer for Question: What is the difference between a class and a struct in C#?