-6

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 2
    https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/readonly – TheGeneral Dec 16 '20 at 05:50
  • @JamalErhoma: if you're on modern C# version, consider using `readonly` structures. 2) Don't invent your own `ToString` method (it's about `Display`). Just override existing one. – Dennis Dec 16 '20 at 06:00
  • https://stackoverflow.com/questions/4464291/why-cant-i-initialize-readonly-variables-in-a-initializer & https://stackoverflow.com/questions/18385248/readonly-field-in-object-initializer & https://stackoverflow.com/questions/3728447/how-do-i-set-a-readonly-field-in-an-initialize-method-that-gets-called-from-the –  Dec 16 '20 at 09:55

1 Answers1

0

Because readonly field can be assigned either when declared, or in it's class constructor

SelfishCrawler
  • 225
  • 2
  • 12
  • This is a fairly low quality answer. – TheGeneral Dec 16 '20 at 06:06
  • The question is - why does readonly field can be assigned somewhere, the answer if fulfilling. Your comment which just throws asking user to another site to read tons of text, taking in mind that links may become inaccessible by time, is not better. – SelfishCrawler Dec 16 '20 at 06:09
  • Mr.General, I thanked you, but I did not find any sign of your response as a sign of accepting it as correct – Jamal Erhoma Dec 16 '20 at 22:51