Private/Public variables

Ask general questions here.
monkey2012
Posts: 77
Joined: Wed Sep 26, 2012 8:15 pm

Private/Public variables

Post by monkey2012 » Tue Sep 12, 2017 6:13 pm

Hi,

Should I use public or private variables in the code module?

string _appStat = "Running";
[TestVariable("58fcdded-b7c1-4f10-88a3-84d53b17daed")]
public string appStat
{
get { return _appStat; }
set { _appStat = value; }
}

public CheckStat()
{
// Do not delete - a parameterless constructor is required!
}

void ITestModule.Run()
{
Mouse.DefaultMoveTime = 300;
Keyboard.DefaultKeyPressTime = 100;
Delay.SpeedFactor = 1.0;

if (appStat.Equals("Failed"))
{
// Close app
}
}


Or if (_appestat.Equals("Failed"))
Any differences if used (_appestat) or (appStat) in this case? Which one do you recommend?

Thanks

jma
Posts: 111
Joined: Fri Jul 03, 2015 9:18 am

Re: Private/Public variables

Post by jma » Wed Sep 13, 2017 1:56 pm

Hi monkey2012,

If all you are doing is reading or writing a value to this variable, it won't make a difference. I would suggest having a look at the following discussions on stackoverflow:
https://stackoverflow.com/questions/196 ... y-accessor
https://stackoverflow.com/questions/414 ... in-c-sharp

Personally, I prefer accessing the public property ("appStat" in your case).

I hope that helps!

monkey2012
Posts: 77
Joined: Wed Sep 26, 2012 8:15 pm

Re: Private/Public variables

Post by monkey2012 » Thu Sep 14, 2017 6:39 pm

Hi Jma,

Thanks for info and your suggestion.

Thanks

krstcs
Ranorex Guru
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Private/Public variables

Post by krstcs » Thu Sep 14, 2017 7:48 pm

For a class variable, you should try to use the property accessors (get/set) whenever possible (note that this doesn't ALWAYS apply...). This allows you to ensure that no matter where you use the variable it is always accessed the same way. It also means that any transforms or calculations can be done in the get/set and you won't have to change any other code. You can also set the access level (public/protected/private) individually on the get/set so only the parts that you want are available external to the class. And, it also means that you can have multiple accessors for the same base variable, but you can give them names that represent the different transforms being done.
Shortcuts usually aren't...