Dot Net Solutions
George V Place,
4 Thames Avenue
Windsor
Berkshire
SL4 1QP
Great Britain
0845 402 1752
GEO: -0.606174, 51.4843
 
 
 
 

Quick: ReadOnlyDictionary 

Tags: Code

I've seen a few posts on other blogs commenting on the lack of a ReadOnlyDictionary in the .NET framework, often with implementations which wrap a regular Dictionary and prevent modification. I thought I'd point out a solution to this problem which is provided in the Base Class Library:

IEnumerable<KeyValuePair<TKey, TValue>>

That's it. And it's what's returned if you call dictionary.AsEnumerable(). The consumer of your class can convert it back into a Dictionary by passing it into one of the Dictionary constructor overloads, or by calling the ToDictionary LINQ extension method.

The same is true of all collection classes: if you don't want people to modify your internal List, Collection, Array, Hash Set or whatever it may be, just call AsEnumerable and give them that; they can convert it into whatever type of collection they like at their end.

BTW, the same is true of function parameters: if all you're going to do is foreach through a list, then your parameter type should be IEnumerable<T>, rather than List<T> or IList<T>.

Published: 21 Jan 2010  03:09
0  Comments  |  Trackback Url  | 0  Links to this post | Bookmark this post with:        
 
 
 
 

Links to this post

No linkbacks added
 
 
 
 

Comments

No comments added yet
 
 
 
 

Post comment

Name *:
URL:
Email:
Comments:


CAPTCHA Image Validation


 
 
 
 

Related posts

- My .NET Framework – Part 2: Properties - Published: 19 Jan 2010
- My .NET Framework – Intro & Part 1 - Published: 15 Jan 2010