Why the value I assigned to a variable is gone?

  • A+
Category:Languages

I assigned the value of a variableA to another form variableB. Why both the variables are empty after that I clear the variableA?

Before execute entries.clear() 

Why the value I assigned to a variable is gone?

After execute entries.clear() 

Why the value I assigned to a variable is gone?

 


Both frm5.entries and entries refer to the same object, due to this code earlier:

frm5.entries = entries; 

The value of each variable here is just a reference to an object - like two pieces of paper with the same house address on. Your call to entries.Clear() is like saying "Go to the house with the address written on the piece of paper called entries, and remove all the furniture." If you then go to the house with the address written on the piece of paper called frm5.entries, you'll see an empty house.

This is how reference types work in .NET, and it's crucial to understand that in order to make progress in any .NET language. I have a page on the topic with a lot more information, and there's a Stack Overflow question you may find useful too.

Here's an example demonstrating the point:

using System; using System.Collections.Generic;  class Test {     static void Main()     {         List<string> x = new List<string>();         List<string> y = x;         // x and y now refer to the same list...          x.Add("foo");         Console.WriteLine(y.Count); // 1          y.Clear();         Console.WriteLine(x.Count); // 0          // Changing x or y to refer to a different list         // *doesn't* change the other variable         x = new List<string>();         x.Add("bar");         x.Add("baz");          Console.WriteLine(y.Count); // 0     } } 

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: