C # auto property

Is the C # 3.0 automatic property fully replaceable?

I mean, I can directly use the property instead of serving it, since the property serves as a private support field (sorry, as I understand it).

int a; public int A { get;set; } 
+3
source share
3 answers

When you access a property from code - inside or outside the class - it is always available as a property. In most cases, this doesn’t matter, but it means that you cannot pass it by the link that you could do if it were a field.

The only piece of code that directly accesses the base field (reflection to the side) is the property itself.

This property is clean and simple. It is not available as a field - it is available as property. The C # compiler does not replace access to them using field access. Access to it is always access to properties. Of course, it can be built in by the JIT compiler, but nothing special. As for the CLR, this is just a normal property (to which the [CompilerGenerated] attribute applies).

But in order to answer your initial question - yes, an automatic property means that you do not need to declare a support field yourself. Effectively this:

 public int Foo { get; set; } 

translates to

 private int <>Foo; // Or some other unspeakable name public int Foo { get { return <>Foo; } set { <>Foo = value; } } 

You cannot access the generated field directly in C # code, since it has an inexpressible name. You will see that this is present if you examine the type with reflection, although the CLR does not distinguish between an automatically implemented property and a "normal" one.

+7
source

Yes, an automatic property has its own storage field.

When you define an automatic property, the compiler will create the necessary support field. It is not available as a field from regular code, but it is, and you can access it through reflection if you really need it.

See this guide for more details: http://msdn.microsoft.com/en-us/library/bb384054.aspx

+7
source

There is some compiler magic, e.g. with delegates, etc. You can see this as if the compiler was taking responsibility for creating the necessary code, which otherwise you would have to enter explicitly.

0
source

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


All Articles