maxp
maxp

Reputation: 25161

Access automatic property - c#

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;}}

Upvotes: 5

Views: 782

Answers (2)

xanatos
xanatos

Reputation: 111940

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".

Upvotes: 3

BoltClock
BoltClock

Reputation: 724372

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; }
}

Upvotes: 6

Related Questions