C
C#4mo ago
Trou

✅ Return readonly property

Hello, i have a an question about returning class property as readonly(immutable) outside ? for example how to implement this C++ code in C#
const map<Command, Container>& getCommands() const { return commands }

//
auto m = c.getCommands();
m.insert(....) // error
const map<Command, Container>& getCommands() const { return commands }

//
auto m = c.getCommands();
m.insert(....) // error
here is some part of my C# code
public Dictionary<Command,Container> GetCommands()
{
return _commands;
}

privateDictionary<Command, Container> _commands;
public Dictionary<Command,Container> GetCommands()
{
return _commands;
}

privateDictionary<Command, Container> _commands;
i wanna block Add operations outside class var m = c.getCommands(); m.Add(... I searched google and stackoverflow but I couldn't find exactly I wanted, then when I asked chatgpt got anwswer that I should use IReadOnlyDictionary<T>. Is this the best practice?
2 Replies
Pobiega
Pobiega4mo ago
Correct. Mutability in C# comes down to the type system
Trou
Trou4mo ago
ok, thanks
Want results from more Discord servers?
Add your server