Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a dictionary by ref

Tags:

c#

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.

like image 340
omri_saadon Avatar asked Sep 23 '26 11:09

omri_saadon


1 Answers

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
like image 171
Jon Skeet Avatar answered Sep 26 '26 00:09

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!