Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieving a value in one class that is set in another

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

    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);
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading