Home
Blog
When to Use a Struct in C#
Updated
Dot Net Perls

When to Use a Struct in C#

When I was first learning how to program C#, I wanted to use structs in strategic places. It seemed to make sense—structs could somehow make my programs better and speed them up somehow.

Over time, I started to realize most of the places I used structs would have been better off (or just as well-off) with classes. Structs are a way to have a type that is stored inline, without a reference to the heap memory. In .NET things like ints, DateTime, or KeyValuePair are structs—these are all types that require minimal memory.

Unless you have a need to create a new numeric type, it is best to avoid structs. Here are some drawbacks of structs:

They are often larger than a reference to the heap, so when we pass them to a method, or copy them to a List, more memory needs to be copied—this causes slowdowns.
If the struct is larger than a reference, a List of structs may be larger in memory (and slower) than a List of class references.

The C# language is designed mostly around classes. Structs are more of a feature that is needed for the standard library—to create types like int, DateTime, or KeyValuePair. If you have types similar to those, a struct can help performance slightly, but even then a class may be superior. In general, classes are preferred.

Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
An RSS feed is available for this blog.
Home
Changes
© 2007-2025 Sam Allen