That is the purpose of private
fields - they cannot be accessed from other classes. But making the field public
is not the way to go. Usually C# developers wrap the field in a public
property, that can have validations o transformations implemented. This is almost what you did, you didn't explicitly make the property public
, which is necessary.
The default member visibility is private
so you should make your property public
:
public class GameData
{
private static int numberOfPlayersInOfflineGame;
public static int NumberOfPlayersInOfflineGame
{
get
{
return numberOfPlayersInOfflineGame;
}
set
{
numberOfPlayersInOfflineGame = value;
}
}
}
But I am against what @Agent_Orange suggests: Do not make your field public
as well! That completely defeats the purpose for creating a property. Any code could then bypass potential validations in the property setter to set the numberOfPlayersInOfflineGame
to any unexpected value like -100
.
As @Jon Skeet notes - if you don't perform any additional tasks in the getter and setter of the property, you could simplify your code by making it an auto-property:
public class GameData
{
public static int NumberOfPlayersInOfflineGame { get; set; }
}
You can now use the property instead of the field both in your class code and outside of the class. If you later decide to add some validations, you can always go back to having a property backed by a private field.