0

Honestly,I know I can miss the set clause to avoid user setting my property. Like below code:

private Dictionary<int, string> _configurations = new Dictionary<TState, StateConfiguration>();

public Dictionary<int, string> Configurations { get { return _configurations; } }

So, we can't run below code at outer code:

XXX.Configurations = new Dictionary<int, string>();

It prompts :

Property or indexer 'XXX.Configurations' cannot be assigned to -- it is read only

But we can change the value like below code:

XXX.Configurations.Add(1,"1000")

Because dictionary is a reference type.

So how can I avoid this. Let user access the reference property with no changing.

bwegs
  • 3,769
  • 2
  • 30
  • 33
roast_soul
  • 3,554
  • 7
  • 36
  • 73
  • possible duplicate of [Is there a read-only generic dictionary available in .NET?](http://stackoverflow.com/questions/678379/is-there-a-read-only-generic-dictionary-available-in-net) – Prix Mar 09 '15 at 13:56
  • possible duplicate of [How to expose a collection property?](http://stackoverflow.com/questions/35007/how-to-expose-a-collection-property) – kjbartel Mar 09 '15 at 14:20

2 Answers2

3

You could try returning the dictionary as read-only:

public IDictionary<int, string> Configurations 
{ 
  get { return new ReadOnlyDictionary(_configurations); } 
}
matt
  • 9,113
  • 3
  • 44
  • 46
  • ReadOnlyDictionary does not inherit from Dictionary – AK_ Mar 09 '15 at 14:34
  • 1
    Personally, I would recommend returning an [IReadonlyDictionary](https://msdn.microsoft.com/en-us/library/hh136548.aspx). I'm not a fan of treating `ReadOnlyDictionary`; I find `IDictionary` to be a bit dangerous, since it throws an exception on modification rather than outright disallowing it; too much code ignores the the `IsReadOnly` property. – Brian Mar 09 '15 at 16:11
2

It sounds like you want to expose a ReadOnlyDictionary. You could create a new one each time the property is accessed, or you could have two fields - one for the writable dictionary (which you never expose) and one for the read-only wrapper.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194