Assuming you only have immutable types
and you have all your code up to date to C# 7.3 and your methods are using the in
keyword for inputs
Why would you ever use a class instead of a readonly struct?
The downside of using structs was that copying was expensive, but assuming you prevent any copy (defensive compiler copy or expressed by code), readonly structs allow you to only copy the reference (as classes do) and avoid heap allocation and pressure on the garbage collector.
Excluding special cases (which I guess it could be a very large object that won't fit on the stack) would you use readonly struct as first choice normally?
The case I am interested in is where they are used as data containers.
The readonly keyword is a C# modifier used to limit access to all the data members of a struct. If the readonly modifier is used in the declaration of a struct, then: The members of the struct are read-only. None of the members can have setters. A parameterized constructor is used to initialize the data members.
A class is a user-defined blueprint or prototype from which objects are created. Basically, a class combines the fields and methods(member function which defines actions) into a single unit. A structure is a collection of variables of different data types under a single unit.
In classes, two variables can contain the reference of the same object and any operation on one variable can affect another variable. In this way, struct should be used only when you are sure that, It logically represents a single value, like primitive types (int, double, etc.). It is immutable.
The readonly keyword is a modifier that can be used in four contexts: In a field declaration, readonly indicates that assignment to the field can only occur as part of the declaration or in a constructor in the same class.
structs should not be looked on as "cheap objects"; they have similar feature sets that are overlapping in some areas and disjoint in others. For example:
Foo
can't contain a Foo
if it is a struct) - there are othersAlso, note that until very recently ("ref returns" and "ref locals") it was very hard to achieve some parts of "readonly structs allow you to only copy the reference"; this is now much simpler.
But frankly, in most scenarios POCOs are just easier to work with, and are fine for most application-code scenarios.
There are certainly times when structs are an amazing choice. It just isn't every time. I would however, support the notion that if you're going to use a struct
, it should be either a readonly struct
(by default) or a ref struct
(if you know why you're doing it); mutable non-ref
structs are a recipe for pain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With