Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the out parameter in Dictionary.TryGetValue point by reference to the value [closed]

Consider if I have a Dictionary<Key,List<item>> TestDictionary

If I do:

List<item> someCollection;
TestDictionary.TryGetValue(someKey,out someCollection); //assuming that someCollection will not return null;
someCollection.add(someItem);

Will the object someItem be added to the collection in the Dictionary value TestDictionary[someKey] ?

like image 840
Siraj Mansour Avatar asked Nov 26 '12 08:11

Siraj Mansour


People also ask

How does TryGetValue work C#?

TryGetValue Method: This method combines the functionality of the ContainsKey method and the Item property. If the key is not found, then the value parameter gets the appropriate default value for the value type TValue; for example, 0 (zero) for integer types, false for Boolean types, and null for reference types.

How does C# dictionary work?

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.

Is dictionary a reference type C#?

It is a class hence it is a Reference Type.

What is .NET dictionary?

Dictionary in . NET represents a collection of key/value pairs. In this tutorial, learn how to create a dictionary, add items to a dictionary, remove items from a dictionary, and other dictionary operations using C# and . NET. C# Dictionary class is a generic collection of keys and values pair of data.


2 Answers

Yes, you will have a reference of the object if it is a Ref type, and of course a copy if it is a Value type

like image 66
AlexH Avatar answered Sep 26 '22 15:09

AlexH


Jon Skeet posted great article on this regard. But, anyway, here code snippet that can help you:

class Item
{}

void Main()
{
    var dictionary = new Dictionary<int, Item>();
    dictionary[1] = new Item();

    Item i1;
    Item i2;

    dictionary.TryGetValue(1, out i1);
    dictionary.TryGetValue(1, out i2);

    Debug.Assert(object.ReferenceEquals(i1, i2));
}
like image 29
Sergey Teplyakov Avatar answered Sep 24 '22 15:09

Sergey Teplyakov