[C#] Get values from other object instance

Junior Spellweaver
Joined
Sep 15, 2004
Messages
190
Reaction score
0
Ok guys, i've got this problem going that drives me crazy, ill try to explain the best as i can so you can understand.
The problem is, when for example i create a new class:

Code:
class Customer
{
    public string someName = "";
    public void Name(string yourName)
    {
        someName = yourName;
    }
}

Then in Class1.cs i make a new instance of the object:

Customer Cust = new Customer();

And then i assign some string value to it:

Cust.Name = "Michael Jackson";

So now the string someName in the class customer contains the value "Michael Jackson"

Now, i create another class named Class2.cs.
And this is where i've got a problem.

How do i get the value from someName out of the instance of the object Cust created in Class1.cs into Class2.cs?

Because i would have to create an new instance of the Customer class in Class2.cs first before i can call the function:

Customer Cust = new Customer();

As like above note the "new" keyword, this will create a new instance of the object, and thus someName will no longer contain "Michael Jackson".

Is there anyway to not make a new object, but rather re-use an existing one or something along those lines?

Any ideas?

Thanks for your time.
 
Last edited:
Copying

Code:
class Customer
{
    public string someName = "";
    public void Name(string yourName)
    {
        someName = yourName;
    }
}

class Class1
{
	Customer c = new Customer();
	
	public Class1()
	{
		c.Name("Micheal Jackson");
	}
	
	public Customer GetCustomer()
	{
		reuturn c;
	}
}

class Class2
{
	Customer c = new Class1().GetCustomer();
	
	public Class2()
	{
                Console.WriteLine("Old name: {0}.", c.someName); // Micheal Jackson
		c.Name("Homer Simpson");
                Console.WriteLine("New name: {0}.", c.someName); // Homer Simpson
	}
}
 
Last edited:
Then in Class1.cs i make a new instance of the object:


Code:
Customer Cust = new Customer();
And then i assign some string value to it:
Code:
Cust.Name = "Michael Jackson";
So now the string someName in the class customer contains the value "Michael Jackson"

This is incorrect, what is correct:
Code:
Cust.someName = "Michael Jackson";
//Or
Cust.Name("Michael Jackson");

:)
 
Thanks for the reply's!

The answer was to make a new global static object:

public static Customer myCustomer = null;

Then, in your form_load fuction, or any other fuction that you desire you put:

myCustomer = this;

Then from an other classfile you can call the global static and retrieve all existing values.

Anyways, thanks for your input AJ ;)

This is incorrect, what is correct:
Code:
Cust.someName = "Michael Jackson";
//Or
Cust.Name("Michael Jackson");

:)

Indeed, my bad, didn't test the code, just typed it out.
 
Back