C#C
C#4mo ago
30 replies
Jason_Bjorn

How to make it so that the user can't modify o._d

using System.Text;

Outer o = new();
Middle m = o.GetThing("one");
m.Arr.Add(4);
Console.WriteLine(o); // output is key: one, value: 2, 3, 4

class Outer
{
    private Dictionary<string, Middle> _d;
    public Outer()
    {
        _d = new() { ["one"] = new() };
    }

    public Middle GetThing(string key)
    {
        return _d[key];
    }

    public override string ToString()
    {
        StringBuilder sb = new();
        foreach (KeyValuePair<string, Middle> kvp in _d)
        {
            sb.Append("key: ");
            sb.Append(kvp.Key);
            sb.Append(", value: ");
            sb.AppendLine(kvp.Value.ToString());
        }
        return sb.ToString();
    }
}

class Middle
{
    public List<int> Arr { get; init; }
    public Middle()
    {
        Arr = [2, 3];
    }

    public override string ToString()
    {
        return string.Join(", ", Arr);
    }
}
Was this page helpful?