What's the difference between { get; } vs implementing a "getter method"

Hi all,

Pretty basic programming question here, but one I haven’t found a great answer to.

In this lecture, Nathan uses {get;} to access the SelectedUnits list, which he makes public (UnitSelectionHandler.cs). Then he writes a method GetUnitMovement() to return unitMovement (Unit.cs).

I’m familiar with both methods, but what’s the reasoning behind choosing one over the other? I tend to avoid implementing public variables with {get; set;} mostly because I don’t understand the structure well.

I too would like to know the reason behind this.

1 Like

Hi Tom,

Functional-wise and performance-wise they are the same, so you can do either interchangeably.
Specifically that { get; } syntax (without { set; }) makes it only public for reading if it was not a reference type (which it is, and thus get allows to update it as well, though not replace it).
It’s more common to use C# properties (this is why they are implemented in the language) than Java-like getters/setters (like the GetUnitMovement() above). But you rather choose what you prefer and stick with it for readability and order. It’s a bad practice to set public fields, so even when you don’t have any logic in the get/set you should prefer a private/protected field with relevant public properties if they are to be accessed from the outside.

I for one, made all the getters functions in the tutorials into properties (e.g public UnitMovement unitMovement { get => _unitMovement; }), and usually prefer setter functions if they involve logic (though it can be written in { set; } as well).

I think the usual practice is to make it a property by using {Get;} because this practice is newer, clearer, utilizes less code, and concentrates the relevant information all in one place. As far as I know, it’s mostly about clarity, writing less frivolous code, and keeping to modern C# standards as the language improves.

However, Unity’s inspector can’t read a public property, even with [SerializeField]. So we have to make this a standard public variable if we want it to be populated inside Unity’s inspector. Since you don’t want to access public variables from other scripts, as a general rule, you’ll still need a separate Property or method declared to access the variable via code.

I think that’s why he did it a different way in this section. Because he couldn’t do it strictly the way he did before. Unity wouldn’t see the property. In future Unity versions, this may change.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms