Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# automatic property

Does the automatic property of C# 3.0 completely replace the filed?

I mean,I can directly use the property instead of filed as property serves as private backing field.(sorry,I understand like that only).

int a;

public int A
{
  get;set;
 }
like image 929
user196546 Avatar asked Feb 11 '26 18:02

user196546


2 Answers

When you access the property from code - whether inside or outside the class - it is always accessed as a property. In most cases, this is unimportant - but it does mean that you can't pass it by reference, which you would be able to do if it were a field.

The only piece of code which accesses the backing field directly (reflection aside) is the property itself.

It is a property, pure and simple. It isn't available as a field - it's available as a property. The C# compiler doesn't replace accesses to it with field accesses. Accesses to it are always property accesses. It may well be inlined by the JIT compiler of course, but that's nothing special. As far as the CLR is concerned it's just a normal property (which happens to have the [CompilerGenerated] attribute applied to it).

But to answer your original question - yes, the automatic property means you don't need to declare the backing field yourself. Effectively, this:

public int Foo { get; set; }

is translated into

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, as it has an unspeakable name. You'll see it's present if you examine the type with reflection though - the CLR doesn't distinguish between an automatically implemented property and a "normal" one.

like image 185
Jon Skeet Avatar answered Feb 15 '26 13:02

Jon Skeet


Yes, the automatic property has its own holding field.

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

Please see this guide for more info: http://msdn.microsoft.com/en-us/library/bb384054.aspx

like image 39
Brian Rasmussen Avatar answered Feb 15 '26 11:02

Brian Rasmussen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!