Hi!
I'm trying to access a private field for an existing object. As a student of C# I want to use best practises. But have stumbled upon some questions.
I want to access the bool value of playerIsComputer from the object Player.
I'm a bit confused however about the auto property vs non-auto.
Using the non-auto property let me access the field. However, will the field still be protected? Meaning I'm not actually messing with the backing field? Thus an okey solution according to best practise?
Using the auto-property wont let me access the field at all:
And this is what I'm trying to achieve. To check wheater or not the player is a computer or not using an if-statement:
I'm trying to access a private field for an existing object. As a student of C# I want to use best practises. But have stumbled upon some questions.
I want to access the bool value of playerIsComputer from the object Player.
I'm a bit confused however about the auto property vs non-auto.
Using the non-auto property let me access the field. However, will the field still be protected? Meaning I'm not actually messing with the backing field? Thus an okey solution according to best practise?
Using non-auto property:
class Player {
// Backing fields
private bool playerIsComputer;
// Property
public bool PlayerIsComputer {
get { return playerIsComputer; }
set { playerIsComputer = value; }
}
}
Using the auto-property wont let me access the field at all:
Auto-property:
class Player {
private bool PlayerIsComputer { get; set; }
}
And this is what I'm trying to achieve. To check wheater or not the player is a computer or not using an if-statement:
C#:
foreach (var player in players)
{
if (player.PlayerIsComputer)
{
// Do something
}
}