Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Properties in c# in Unity (Unity5) - can you avoid the backing variable

Tags:

c#

unity3d

With Unity5 (it's hard to know exactly what version of c#/Mono/.Net is being used), we do properties exactly like this:

private int _distance;
public int Distance
    {
    private set
        {
        _distance = value;
        controls.Blahblah(_distance);
        }
    get
        {
        Debug.Log("hah!);
        return _distance;
        }
    }

But consider the new "automatic properties" in c#, which seem to be like

 public int Distance {get; set;}   // ?

but I don't know how to "do something" in the getter/setter ??

Or in other words, is there a way to auto generate the backing variable (as well as the convenience -- to keep it private) when "manually" making a Property?

To repeat since this was marked as a duplicate, how can I "do stuff" in the automatic Property idiom during the getter/setter ...

... or conversely ...

how to hide, get rid of, or automatically supply the backer if you write your own "manual" properties?

Note that of course you or another programmer can accidentally touch the _underscore backing variable: is there any way at all to avoid that??

like image 760
Fattie Avatar asked Jan 06 '23 14:01

Fattie


2 Answers

You can't use auto-properties if you want to "do something" in the getter/setter, apart from just assigning to the field. For the use-case described by your example code, auto-properties are not an option. There is nothing wrong with having an explicit backing field.

like image 51
sara Avatar answered Jan 09 '23 03:01

sara


If you have only the private variable without any other logic then you can use Auto properties.

Class Something something
{
    public int Distance
    {
    private set
     {
       _distance = value;
     }
    get
     {
       return _distance;
     }
    }

// Keep this at the end of the class
// In visual studio you can collapse region and wont attract
// attention/distracting in your editor.

#region data members
private int _distance;
#endregion data members
}

you can replace it with public int Distance {get; set;}

But if you do other actions like logging, then you have to write it in traditional way.

Edit

Its all coding practice. I generally enclose the private variables in a #region p ...#endregion. And use only the Properties for setting - Distance and have never used _distance. Its more of a coding practice than an actual fix for what you are doing.

One more reason I do that is - In WPF we would need to call NotifyPropertyChanged event whenever we set the properties. It will be a bug if I don't use the property name. So this habit of using Properties over private variables stuck.

You cannot make the variable un-discoverable, just grouping them together for easy readability and Yes this is human enforced practice.

like image 22
Carbine Avatar answered Jan 09 '23 04:01

Carbine