M
M
MishkaVNorky2018-12-26 09:18:34
C++ / C#
MishkaVNorky, 2018-12-26 09:18:34

property and fields?

Hello. My question is does Property allocate memory?
As I understand it should not because there is no point, then it was more logical to use methods.
But in the new version of C#, you can use auto Property. That is, propert can be immediately a variable.

int CurrentHealth { get; set; }
CurrentHealth = 100;

int CurrentHealth 
{

get { .. }
set { ... }

}

When does Property allocate memory?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexey Pavlov, 2018-12-26
@MishkaVNorky

Yes, when creating an autoproperty, a hidden variable is created - the data must be stored somewhere.
This variable is created with a tricky name (with characters forbidden in c# in the variable name). You can see it this way:

class TestClass
{
    private int _a;
    public int A
    {
        get { return _a; }
        set { _a = value; }
    }

    public int B { get; set; }
}

var testClass = typeof(TestClass);
var fields = testClass.GetFields(BindingFlags.NonPublic | BindingFlags.Instance);
foreach (var fieldInfo in fields)
{
    Console.WriteLine(fieldInfo.Name);
}
// результат:
// _a
// <B>k__BackingField

M
Meloman19, 2018-12-26
@Meloman19

Properties are just an abstraction. Any property with a getter and a setter essentially expands into two ordinary methods. For the program, they are not distinguished by anything special, only the programmer needs it.
In these same getters and setters, you can work with fields, as in any other class method.
An autoproperty is just a simplification if you want a property that has no other logic other than setting the value of one field. Behind the scenes, an autoproperty simply creates a field on its own and two (or one) methods that return (or set) that field's value.
As for memory: the field takes up space in memory, and each instance has its own place. Property getters and setters, like regular methods, only once in memory.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question