Properties and Encapsulation
Get-Only Properties
A get-only property can be assigned in a constructor and read afterward.
Get-Only Properties
GetOnlyProperties.cs
using System;
class Badge
{
public string Label { get; }
public int Level { get; }
public Badge(string label, int level)
{
Label = label;
Level = level;
}
}
class Program
{
static void Main()
{
int level = ;
Badge badge = new Badge("helper", level);
string summary = badge.Label + ":" + badge.Level;
Console.WriteLine($"level={level}");
Console.WriteLine($"summary={summary}");
}
}
using System;
class Badge
{
public string Label { get; }
public int Level { get; }
public Badge(string label, int level)
{
Label = label;
Level = level;
}
}
class Program
{
static void Main()
{
int level = ;
Badge badge = new Badge("helper", level);
string summary = badge.Label + ":" + badge.Level;
Console.WriteLine($"level={level}");
Console.WriteLine($"summary={summary}");
}
}
using System;
class Badge
{
public string Label { get; }
public int Level { get; }
public Badge(string label, int level)
{
Label = label;
Level = level;
}
}
class Program
{
static void Main()
{
int level = ;
Badge badge = new Badge("helper", level);
string summary = badge.Label + ":" + badge.Level;
Console.WriteLine($"level={level}");
Console.WriteLine($"summary={summary}");
}
}
get-only property
A get-only property protects a value from later assignment outside the class.