Search code examples
c#intermediate-language

Performance and compilation of null propagation operator


This is specifically referring to some C# properties I want to rewrite.

Example of one of the original properties:

public double? PartQuantity
{
    get
    {
        if( MaintenanceRequestPart != null )
            return MaintenanceRequestPart.ReportedQuantity.HasValue
                ? (double?)MaintenanceRequestPart.ReportedQuantity.Value
                : null;

        return null;
    }
}

What this will be changed to:

public double? PartQuantity => MaintenanceRequestPart?.ReportedQuantity;

note 1: MaintenanceRequestPart can be null

note 2: MaintenanceRequestPart.ReportedQuantity is a nullable double

Will this save or add some operations/branching/overhead? I'm curious as to what the ?. operator actually translates into behind the scenes once it's turned into intermediate language.


Solution

  • This is perfectly fine. The only difference is that it will copy reference of this variable on IL level. So this is basicaly means that:

    public double? PartQuantity => MaintenanceRequestPart?.ReportedQuantity;
    

    Is the same as:

    public double? PartQuantity 
    {
        get
        {
            var value = MaintenanceRequestPart;
            return value == null ? null : value.ReportedQuantity;
        }
    }
    

    Why did it do this additional copying? The answer is pretty simple - to capture value for atomic desicion if this value accessed from different threads. It is very useful when you work with events (so it will not throw NullReferenceException in the middle of "?" operator):

    public event EventHandler OnSomethingHappened;
    ...
    OnSomethingHappened?.Invoke(this, new EventArgs());
    

    But, do not fear, it will not have reasonable impact on performance.

    Verdict: you can do this refactoring without losing a thing