Search code examples
c#inputconsole

C# store an integer input in class for recall later?


I want to store the integer input from a user as an instance level variable so that I can recall it at a later time

So far in Class.cs I have:

namespace home
{
    internal class Class
    {

        public string id;
        

        public Class()
        {

            Console.WriteLine("please enter ID");
            string input = Console.ReadLine();
            int id;
            Int32.TryParse(input, out id);
        }
    }
}

And then in program.cs:

using home; 
Class object1 = new Class();
Console.WriteLine(object1.id);

This allows the user to input the number, however, it does not print the number afterwards.

I have managed to recall a string input such as a name, I just cannot get it to recall a number input, so everything works fine except for the number being saved and displayed at a later time. If I put Console.WriteLine(id); in the class.cs then it will display it, but obviously it's just displaying the input and not really storing it.


Solution

  • You are saving the result of the TryParse call in the "int id" variable which is declared inside the Class constructor and therefor released once the constructor finishes executing. To fix your code, you should be saving your id in the "string id" field declared in the Class class.

    If you want to access a member variable ( variable declared in a class ) that shares its name with a local variable ( variable declared in a method ) you have to prepend it with "this."

    Now I'm not sure if you meant to declare this as a string, but if you did you can just do this

    internal Class()
    {
    
        public string id;
    
        public Class()
        {
           Console.WriteLine("please enter ID");
           id = Console.ReadLine();
        }
    }
    

    If you meant to declare it as an int you can instead do this

    internal Class()
    {
    
        public int id;
    
        public Class()
        {
           Console.WriteLine("please enter ID");
           string id = Console.ReadLine();
           this.id = int.Parse(id);
        }
    }