Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Set from another class and Get from another class

Tags:

c#

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?

like image 547
Phong Nguyễn Avatar asked Sep 06 '25 05:09

Phong Nguyễn


1 Answers

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!

like image 187
Sweeper Avatar answered Sep 07 '25 21:09

Sweeper