Perhaps this question some of you have no meaning to it, but I am baffled if any of you can answer me.
Assuming that I have this structure and it has a field or several fields for reading only, how can I assign a value to it through the constructor.
struct PointWithReadOnly
{
// Fields of the structure.
public int X;
public readonly int Y;
public readonly string Name;
// Display the current position and name.
public readonly void Display()
{
Console.WriteLine($"X = {X}, Y = {Y}, Name = {Name}");
}
// A custom constructor.
public PointWithReadOnly(int xPos, int yPos, string name)
{
X = xPos;
Y = yPos;
Name = name;
}
}
To use this struct, add the following :
PointWithReadOnly p1 = new PointWithReadOnly(50,60,"Point w/RO");
p1.Display();
The field is read-only, so how does the code work in this way?