0

In a third party project I have stumbled upon a C# code pattern that is unknown to me, and which I wasn't able to find anything about online, though the code compiles just fine. I have added comments to these two lines I do not get:

public class SimulationSceneContext: BaseSceneContext, ISceneContext {
    
    protected override string backgroundLayerName => "SimulationBackground";    // is that a lambda override?

    public SimulationSceneContext(SimulationData data): base(data) {}    // what kind of constructor is that??
}

Base class:

public abstract class BaseSceneContext {
    
    protected abstract string backgroundLayerName { get; }

    public BaseSceneContext(SimulationData data) 
    {
        // ...
    }

    // ...
}

I was unsure as to how to phrase this question, if anyone has a suggestion for a better title I am happy to rename it, so that others stumbleing on such a pattern are able to find it.

Florian Wolf
  • 171
  • 7
  • 2
    It's overriding a property using an ***expression-bodied member***. It is *not* a lambda, even though it uses the same symbol (`=>`). – madreflection Oct 19 '20 at 16:17
  • 2
    The second is just a constructor which has an empty body and calls the constructor of the base class with same argument – Döharrrck Oct 19 '20 at 16:19
  • 1
    Since the base class does not have a parameterless constructor the inheriting class has to define a constructor that calls the base class constructor. – juharr Oct 19 '20 at 16:21

1 Answers1

1

As mentioned in comments, it is just overriding the abstract string property to provide the value in concrete implementation. It is a shortcut to writing this:

protected override string backgroundLayerName { get { return "SimulationBackground"; } }

Or this as well is commonly used for similar purpose (but as noted in comments, this causes compiler to auto-create a backing member, so not exactly the same):

protected override string backgroundLayerName { get; } = "SimulationBackground";

The second method will cause the string to be evaluated only once, which could be better in many scenarios. The first method will evaluate the string every time the property is accessed.

Jason W
  • 13,026
  • 3
  • 31
  • 62