C#C
C#2y 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


here is some part of my C# code

 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?
Was this page helpful?