Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Dictionary as a Property

Can someone point me out to some C# code examples or provide some code, where a Dictionary has been used as a property for a Class.

The examples I have seen so far don't cover all the aspects viz how to declare the dictionary as property, add, remove, and retrieve the elements from the dictionary.

like image 225
Anand Shah Avatar asked Jun 11 '09 13:06

Anand Shah


People also ask

Can a dictionary be a property C#?

Item[] Property. This property is used to get or set the value associated with the specified key in the Dictionary. Here, key is the Key of the value to get or set.

How to access dictionary values in C#?

Access Dictionary Elements The Dictionary can be accessed using indexer. Specify a key to get the associated value. You can also use the ElementAt() method to get a KeyValuePair from the specified index.

How a dictionary works in C#?

A dictionary, also called an associative array, is a collection of unique keys and a collection of values, where each key is associated with one value. Retrieving and adding values is very fast. Dictionaries take more memory because for each value there is also a key.


1 Answers

Here's a quick example

class Example {   private Dictionary<int,string> _map;   public Dictionary<int,string> Map { get { return _map; } }   public Example() { _map = new Dictionary<int,string>(); } } 

Some use cases

var e = new Example(); e.Map[42] = "The Answer"; 
like image 198
JaredPar Avatar answered Sep 23 '22 17:09

JaredPar