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()
After execute entries.clear()
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()
After execute entries.clear()
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
}
}
Try frm5.entries = entries.ToArray(); that will copy your collection. I think now you copy reference not the value. Runing Clear() on one varibale results the other will also be empty because it points to the same sapace in memory.
It seems, that entries
is collection, array or List
, or some other.
Anyway, all those are called classes and you can create instances of those classes. Those objects then are reference types, meaning that variable hold just a reference to memory, where the object is "remembered". So, when you assign your variable to other variable, that other variable also holds just a reference to the same memory.
So when you change one variable, underlying object gets changed, so second variable is also influenced as well (all changes made with one variable are reflected in all variables holding the same reference).
I suggest you do some reading on that for better understanding. For example: A deep dive: Value and reference types in .Net
I am not sure about the data type of the entries but if entries variable is DataTable please start using like:
in if block
frm5.entries = entries.Copy();
in else block
frm5.entries1 = entries.Copy();
It will copy solve your problem.