✅ 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:
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 ?
14 Replies
What exactly do you think "capture" means/does here?
hmm it creates a backing field for t ?
yes
in the second case
hmm in second case, we have a backing field only for t, not Data?
but hmm when we say "backing field", what do we mean by that, I mean, Data exist, go we can do something like
Foo.Data
Can we say the following (please can someone confirm):
Backing field just means that a variable stores its own data.
Capture means a backing field is created.
So consider this:
Data has a setter, it stores its own data and so should have a backing field.
t is not captured because we only assigned it to something; it's only used once.
Now this:
Data only have a getter. Data depends on the value of t and doesn't store its own data. So Data doesn't have a backing field.
Value of t is captured though because each time, it should be present so that using something like Foo.Data
can retrieve the value?yes, because
Data
is just a getter, no setter. it has no state, its just a method
Backing field just means that a variable stores its own data.a backing field is only a thing for properties that have state
yeahh I see, backing field are used for properties which have a state?
specifically for primary constructors, capture means a field is created
yes
yep I see, it's clearer now when we think of it in form of states
hmm I think it's clearer now, will come back if I have other doubts, thanks !
use sharplabs btw
yeah just used it, it helped me a lot about backing field and all, just started to love using it 😂
yep, thanks !!
Capture means a backing field is createdTechnically speaking, no. All you can say for certain is that it's captured The C# specification makes no guarantees on how a capture is actually stored I might not normally be pedantic like this, but if you're asking about the deep details on what the difference between these concepts are, then you get the pedantry
yep I see