omri_saadon
omri_saadon

Reputation: 10631

Getting a dictionary by ref

I was wondering if a right value of a dictionary can be by ref. so, when i'm changing the value of the dictionary some other value will also will change for example:

double num = 7;
Dictionary<string,double> myDict = new Dictionary<string, double>();
myDict.Add("first",num);
myDict["first"]=4;
// i want num also to change to 4.. is it possible?

thank you for any help.

Upvotes: 2

Views: 147

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500805

No, that's basically not possible. If you want something like that, you'd need a wrapper class type, e.g.

public class Wrapper<T>
{
    public T Value { get; set; }
}

Then you could use:

var wrapper = new Wrapper<double> { Value = 7.0 };
var dictionary = new Dictionary<string, Wrapper<double>>();
dictionary.Add("first", wrapper);
dictionary["first"].Value = 4;
Console.WriteLine(wrapper.Value); // 4.0

Upvotes: 13

Related Questions