In C#, how to forbid user from setting my reference property

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.

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow