© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
2 replies
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?
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

Readonly struct property vs member variable
C#CC# / help
3y ago
❔ How to use a readonly property for binding [AvalonEdit]?
C#CC# / help
3y ago
✅ Readonly methods
C#CC# / help
2y ago
readonly struct and readonly struct instance members (optimization?)
C#CC# / help
4y ago