Structs, C#7 and Performance Improvement 

C# 7 provides a very powerful feature from the performance standpoint. This feature is returning by ref. Essentially this allows for value types to be returned without having to copy them.

The guidelines are normally that you shouldn’t use a struct with too many fields. Various sources quote various size guidelines. Whenever the struct was over the prescribed size it was recommended that you pass it by reference.

With the new syntax for returning types by reference, it’s now more convenient (no more methods returning via out parameter) to use structs. 

In performance critical scenarios where you need to avoid polluting managed heap with too many Gen #0 objects using structs has now become more natural. In the past dealing with structs was somewhat cumbersome if you dealt with a large number of fields and needed to avoid copying of values. 

I have worked on a large application at McLaren – Telemetry Acquisition System that is supplied to all teams. The performance of the application is very critical as it has to process gigabytes of telemetry data. We have used structs extensively to squeeze out every bit of performance from .NET runtime.

I think it’s my second favourite feature after value tuples.

Value Types – When (not) to Use

Just to reiterate – What are the value types (structs, enums)

Value types are cut-down classes.  Imagine classes that don’t support inheritance or finalizers, and you have the cut-down version: the struct.  Structs are defined in the same way as classes (except with the struct keyword), and apart from the some limitations (described below) , structs can have the same rich members, including fields, methods, properties and operators.  

In the previous post I have also outlined several benefits of using value types:

1) They don’t require garbage collection
2) They use less space due to alignment and having no object header
3) Even though they are copied you can still get around the issue by using the ref keyword
4) By default value types are not nulluble, but you can wrap them into Nulluble,  essentially achieving the same semantics as a reference type.

However there are certain major drawbacks using value types:

Continue reading “Value Types – When (not) to Use”

Blog at

Up ↑