I hope you are all doing well.
I’ve been having a small issue in a task for university, I have a variable in a class named Alpha where I want the value to be changed to what is entered by the user. For the second class named Charlie, I want to use the same value entered by the user. I understand why my work doesn’t work but I have no idea if I am missing something fundamental to make it work.
This is just toy code and isn’t my actual work however, this is an accurate reflection of the issue I’m having.
class Alpha
{
public string message = "hello.";
public void Bravo()
{
Charlie charlie = new Charlie();
Console.WriteLine("Enter message here:");
message = Console.ReadLine();
Console.WriteLine("Alpha() says, " + message + ".");
charlie.Delta();
}
}
class Charlie
{
public void Delta()
{
Alpha alpha = new Alpha();
Console.WriteLine("Charlie() says, " + alpha.message);
}
}
class Program
{
static void Main(string[] args)
{
Alpha alpha = new Alpha();
alpha.Bravo();
}
}
>Solution :
you need to pass the alpha instance to charlie
charlie.Delta(this);
and
public void Delta(Alpha alpha)
{
Console.WriteLine("Charlie() says, " + alpha.message);
}
this is because you can have multiple different alphas with different messages. In your currebt code you creat a new alpha that has nothing to do with the one that called charlie.delta.
Another possibility is to have static data. In this case there is only one occurrence of it
class Alpha
{
public static string message = "hello.";
.....
public void Bravo()
{
Charlie charlie = new Charlie();
Console.WriteLine("Enter message here:");
Alpha.message = Console.ReadLine();
Console.WriteLine("Alpha() says, " + message + ".");
charlie.Delta();
}
}
and
public void Delta()
{
Console.WriteLine("Charlie() says, " + Alpha.message);
}