C#C
C#10mo ago
Faker

✅ Backing Field and Primary Constructors

Hello guys, I was reading a bit about backing fields and primary constructors. Can someone explain when is a backing field created and when does a primary constructor argument persist please.

For example, consider the following code:
C#
    private class Node(T t)
    {
        // No capture in this form. Data has a backing field, and you assign t to it.
        public T Data { get; set; } = t;
    }

    private class Node(T t)
    {
        // Capture in this form. Data has no backing field, and t is captured as class state
        public T Data => t;
    }

For the first node class, I understood that t is not captured because we are assigning it directly to Data and we won't really use t later on and so it can be discarded. Data property also has a backing field.

On the other hand, in the second node class, we don't have a backing field but t is captured.

I don't understand why t is captured here and why is a backing field not generated, when is a backing field generated and when is the argument of a primary constructor captured please (just to clarify, a backing field is just a field that stores data, right?).

If we don't have a backing field, this mean, we don't have a private field for something? It's as if the property doesn't exist ?
Was this page helpful?