Properties and Encapsulation
Private Fields
A private field stores data that only the class can change directly.
Private Fields
PrivateFields.cs
using System;
class Score
{
private int points;
public int Points
{
get { return points; }
}
public void Add(int amount)
{
points += amount;
}
}
class Program
{
static void Main()
{
int bonus = ;
Score score = new Score();
score.Add(10);
score.Add(bonus);
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"points={score.Points}");
}
}
using System;
class Score
{
private int points;
public int Points
{
get { return points; }
}
public void Add(int amount)
{
points += amount;
}
}
class Program
{
static void Main()
{
int bonus = ;
Score score = new Score();
score.Add(10);
score.Add(bonus);
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"points={score.Points}");
}
}
using System;
class Score
{
private int points;
public int Points
{
get { return points; }
}
public void Add(int amount)
{
points += amount;
}
}
class Program
{
static void Main()
{
int bonus = ;
Score score = new Score();
score.Add(10);
score.Add(bonus);
Console.WriteLine($"bonus={bonus}");
Console.WriteLine($"points={score.Points}");
}
}
private field
A private field hides storage behind public methods or properties.