Struct vs Class
.NET Programming
C# Data Types
Object-Oriented Programming
.NET Development

What's the difference between struct and class in .NET?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In .NET, both struct and class are used to define types that encapsulate data and related behavior. However, they serve different purposes and have distinct characteristics and use-cases. Understanding the differences between the two is crucial for designing efficient and effective applications. This article explores the key contrasts between struct and class in .NET, with technical explanations and practical examples.

Memory Management

Value Type vs. Reference Type

  • Struct: In .NET, structures are value types. This means they are stored on the stack, though in some cases they might be allocated on the heap inside other objects if they are part of a member field or boxed. When you assign a struct to a new variable or pass it as an argument, a copy of the data is made.
  • Class: Classes are reference types and, therefore, stored on the heap. Variables of a class type store references to the actual object data. Assignments of class instances are reference assignments, meaning multiple variables can refer to the same object.

Here is a simple example illustrating this difference:

csharp
1struct PointStruct
2{
3    public int X;
4    public int Y;
5}
6
7class PointClass
8{
9    public int X;
10    public int Y;
11}
12
13...
14
15PointStruct ps1 = new PointStruct { X = 1, Y = 2 };
16PointStruct ps2 = ps1;
17ps2.X = 10;
18// ps1.X remains 1
19
20PointClass pc1 = new PointClass { X = 1, Y = 2 };
21PointClass pc2 = pc1;
22pc2.X = 10;
23// pc1.X changes to 10

Performance Considerations

  • Struct: Generally faster when dealing with small amounts of data because they do not require dereferencing and have a more predictable memory allocation pattern. However, excessive copying of large structs can lead to performance penalties.
  • Class: May incur a performance cost due to heap allocation and the need for garbage collection. However, for larger or more complex objects, classes are often more efficient because they avoid repetitive copying operations.

Immutability and Design

Design Recommendations

  • Struct: Typically reserved for representing lightweight objects such as coordinates, complex numbers, or other data types where small bundles of data are typical. The Microsoft guidelines suggest that structs should be immutable if used.
  • Class: Suitable for larger, more complex data structures or when polymorphic behavior is needed. Classes support inheritance, which is central to object-oriented programming in .NET.

Inheritance

  • Struct: Does not support inheritance other than from System.ValueType, which implicitly inherits from System.Object. You cannot derive a struct from another struct or class, nor can you derive a class from a struct.
  • Class: Supports full object-oriented features, including inheritance, polymorphism, and encapsulation. Classes can inherit from other classes, and virtual methods allow for method overriding.

Default Values

  • Struct: Automatically initializes fields to their default values. For example, numeric fields are initialized to zero.
  • Class: Class fields are initialized to null unless explicitly initialized, which can lead to NullReferenceException if not handled appropriately.

Equality

  • Struct: By default, equality for structs is based on value comparison, meaning all field values must be equal for two structs to be considered equal.
  • Class: By default, equality for classes is based on reference comparison, unless overridden. This means two distinct class instances are usually considered unequal, even if their internal states match.

Table Summary

FeatureStructClass
TypeValue TypeReference Type
MemoryStack (typically)Heap
ImmutabilityShould be immutableMutable (can be made immutable)
InheritanceNo inheritance supportSupports inheritance
Default ValuesAutomatically initializedInitialized to null (reference)
EqualityValue-basedReference-based (by default)
PerformanceFaster for small objectsEfficient for large, complex structures (avoids excessive copying)

Conclusion

Choosing between struct and class in .NET requires careful consideration of the data you're working with and the operations you intend to perform. If you're handling small, immutable data types and performance is a concern, struct might be the right choice. On the other hand, if you require complex objects with polymorphic behavior and dynamic data manipulation, class is preferable.

In practice, understanding the differences between these types will help you make informed decisions in application design, leading to both performance optimizations and cleaner code architecture.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.