Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Possibly silly question about strings and references in C#

Tags:

c#

Good afternoon,

I'm sorry if this question is too silly, but I don't know much (almost anything) about .Net's memory management system, and I really need to clear up this doubt... I have a Dictionary<String, Int32> which I need to use, and now I need a tree whose nodes are labeled with the strings in that same dictionary. Since, of course, I don't want to store redundant information, how can I make sure the node's label point to the same references as the dictionary's keys?

Thank you very much,

like image 620
Miguel Avatar asked Dec 01 '25 17:12

Miguel


2 Answers

Strings ARE reference types, so that would be the default unless you do something that breaks it.

For instance, for an asp.net page (which you didn't specify, I know), the string that's displayed at the client can't have the same reference as the string in the server's memory.

like image 118
Hans Kesting Avatar answered Dec 03 '25 10:12

Hans Kesting


You can use something like this:

TreeNode node = new TreeNode();
node.Text = dictionary.Keys[0];

It will be the same instance.

like image 33
Liviu Mandras Avatar answered Dec 03 '25 08:12

Liviu Mandras



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!