Do empty accessors matter? As for the types of values ​​and their modifications

I have the following code that does not work because "a" is the entered value. But I thought that this would not work even without accessories, but it happened:

class Program
    {
        a _a  //with accessors it WONT compile
        {
            get; 
            set;
        }
        static void Main(string[] args)
        {
            Program p = new Program();
            p._a.X = 5; //when both accessors are deleted, compiler does not
                        //complain about _a.X not being as variable
        }
    }
    struct a
    {
       public int X;
    }

It does not work as "a" - it is a structure. But when I remove the accessors from the _a instance, it works. I do not understand why. Thanks

+3
source share
3 answers

The main feature of value types is that they are copied, not passed by reference.

When you have a value type and an accessor, you have a value type returned by the method that calls the copy (the following two examples are the same):

ValueType Property { get { return x; } } // Will make a copy of x
ValueType Method() { return x; }    // Will make a copy of x

, x. , , , .

{get; } accessor, , :

int field;

ValueType field;

, , , .

+2

.

:

a _a;

, .


: , p._a, . , "" "" _a. , getter.

# , , , p._a.X = 5; int xx = p._a.X; xx 5. . p_.a : -)


,

a _a;

_a - ;

a _a { get; set; }

_a .

a _a { }

.

+1

p._a.X = 5; , p._a a. . , .

+1

Source: https://habr.com/ru/post/1740120/


All Articles