This's Class A
Class A
{
public string uname { get; set; }
public string fname { get; set; }
}
I set values by Class B
Class B
{
private void Main(){
A aGetSet = new A();
aGetSet.uname = "James";
aGetSet.fname = "Blunt";
}
}
But when I get values in Class C, it's always return null
Class C
{
private void Main() {
A aGetSet = new A();
string username = aGetSet.uname;
string fistname = aGetSet.fname;
}
}
Does anyone has solution for this problem?
The aGetSet
declared in B
is an object of A
. The aGetSet
declared in C
is another object of A
. They are completely independent of each other. Changing the values of one of the objects does not affect the values of the other.
To fix this problem, you need to make it so that you are accessing the same instance in B
and C
.
There are lots of ways to do this. I will show you how to use the singleton pattern.
class A
{
public string uname { get; set; }
public string fname { get; set; }
private A() {} // mark this private so that no other instances of A can be created
public static readonly A Instance = new A();
}
class B
{
public void Main(){
// here we are setting A.Instance, which is the only instance there is
A.Instance.uname = "James";
A.Instance.fname = "Blunt";
}
}
class C
{
public void Main() {
B b = new B();
b.Main();
string username = A.Instance.uname;
string fistname = A.Instance.fname;
}
}
Now you just need to call C.Main
to make this work!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With