Page 1 of 1

Private/Public variables

Posted: Tue Sep 12, 2017 6:13 pm
by monkey2012
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

Re: Private/Public variables

Posted: Wed Sep 13, 2017 1:56 pm
by jma
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!

Re: Private/Public variables

Posted: Thu Sep 14, 2017 6:39 pm
by monkey2012
Hi Jma,

Thanks for info and your suggestion.

Thanks

Re: Private/Public variables

Posted: Thu Sep 14, 2017 7:48 pm
by krstcs
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.