Question

So I know in C++ that I should use a GET and a SET function to access my variables from other places. However in C# this seems to be a property. So my question is should I not use functions for my GET and SET and instead use the c# style in Unity3d?

At the moment my code looks like this:

/// <summary>
/// Highest tempruture during the different weathers. 
/// </summary>
[SerializeField]
protected float _fHighestTemp;

/// <summary>
/// This is our GET function for reading the value. 
/// </summary>
public float GetHighestTemp() { return _fHighestTemp; }

/// <summary>
/// This is our SET function this one we use to set the highest temprature we could have during different weather. 
/// </summary>
public void SetHighestTemp(float SetHighestTemp) { _fHighestTemp = SetHighestTemp; }

Is there any downside to using it with functions? (More memory heavy, or anything else) And could if not, why is it better to use the c# way where its properties instead?

Sorry for the noob question but I really would like to know before I go into a Unity project the wrong way and have to go back and redo it all.

Was it helpful?

Solution

In a recent version of C#, I cant remember which, getters and setters for properties have as shortcut an automatically implemented properties syntax.

This

protected int MyInt{get;set;}

Is equivalent to

protected int _MyInt;
protected int GetMyInt(){return _MyInt;}
protected void SetMyInt(int value){_MyInt=value;}

This

private int MyInt{get;set;}

Is equivalent to

private int _MyInt;
private int GetMyInt(){return _MyInt;}
private void SetMyInt(int value){_MyInt=value;}

The following is also valid:

public int MyInt{get;}
public int MyInt2{set;}
public int MyInt3{get;set myMethod(value);}
public int MyInt4{get{return myMethod();}}

OTHER TIPS

Properties are the idiomatic representation of accessors in C#, so yes, you should use them. You can implement your own property accessor methods or use the automatic properties.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top