Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access automatic property - c#

Tags:

c#

properties

Automatic properties were added to the language in about .net 3 which create a 'private' field, anyway, using the code:

public string foo {get;set;}

Is it possible to actually get any sort of reference to this private field?

I want to do something like

public string foo {get{/*some code to check foo for nulls etc*/};set;}

Without losing this automatic property feature and writing something like

private string _foo = null;
public string foo{get{_foo==null?_foo="hello"; return _foo;}set{_foo=value;}}
like image 829
maxp Avatar asked Mar 16 '11 09:03

maxp


People also ask

What is automatic property?

What is automatic property? Automatic property in C# is a property that has backing field generated by compiler. It saves developers from writing primitive getters and setters that just return value of backing field or assign to it. Instead of writing property like this: public class Dummy.

How do you auto implement property?

Auto-implemented properties declare a private instance backing field, and interfaces may not declare instance fields. Declaring a property in an interface without defining a body declares a property with accessors that must be implemented by each type that implements that interface.

Why we use get set property in C#?

A get property accessor is used to return the property value, and a set property accessor is used to assign a new value. In C# 9 and later, an init property accessor is used to assign a new value only during object construction. These accessors can have different access levels.

Where properties can be declared?

1. A property can be declared inside a class, struct, Interface.


2 Answers

The backing field of an automatic property is anonymous; you can't access it from within its getter or setter.

If you need to implement your own logic in your getter or setter, your property isn't considered automatic anymore anyway.

Auto properties are simply there to save the tedium of typing, and eyesore of seeing, multitudes of these:

private object _x;

public object X
{
    get { return _x; }
    set { _x = value; }
}
like image 74
BoltClock Avatar answered Sep 28 '22 04:09

BoltClock


You can't have a an "automatic" get and a "manual" set (or a "manual" get with an "automatic" set). You must have both "manual" or both "automatic".

like image 20
xanatos Avatar answered Sep 28 '22 02:09

xanatos