Master Irfan Elahee
Master Irfan Elahee

Reputation: 185

Adding default values in class c#

I have a simple console program to have the user login, and then have them change their username and password after the login. I want to have the default login as "temp" and default password as "password". I currently have this

using System;

namespace Loginer
{
    class Program
    {
        static void Main(string[] args)
        {

            string input_user="";
            string input_pass="";

            Login user = new Login(input_user,input_pass);
            bool success = false;

            while (success != true){
                Console.WriteLine("Please key in your username: ");
                string temp_user = Console.ReadLine();

                input_user=temp_user;
                Console.WriteLine("Please key in your password: ");
                string temp_pass = Console.ReadLine();
                input_pass=temp_pass;


                if (input_user == "temp" && input_pass =="password"){
                    Console.WriteLine("Log in success.\n");
                    success = true;

                }

                else{

                    Console.WriteLine("Unsuccessful login, try again\n");

                }


            }

            Console.WriteLine("Please change your username and password (for first time login only)\n");
            Console.WriteLine("Please key in your new username: ");
            string input_newuser = Console.ReadLine();

            Console.WriteLine("Please key in your new password: ");
            string input_newpass = Console.ReadLine();

            user.Username=input_newuser;
            user.Password=input_newpass;

   }
  }
}

I have this class:

using System;

namespace Loginer
{
    public class Login
    {
        private string _username;
        private string _password;

        public Login(string username, string password){

            _username=username;
            _password=password;

        }

        public string Username{

            get{return _username;}
            set{_username=value;}
        }

        public string Password{

            get{return _password;}
            set{_password=value;}
        }



    }
}

How do I add the default values in the class, rather than to have it in the main program.

I have tried this in my Login class

set{_username="temp";}
set{_password="password";}

But i am overwriting it whenever i type in the username and password

Upvotes: 0

Views: 152

Answers (1)

Xerillio
Xerillio

Reputation: 5261

If you want Login.Username and Login.Password to have some default values, just set some values on the backing fields. Of course you also need a parameterless constructor for those to have an effect:

public class Login
{
    private string _username = "temp";
    private string _password = "password";

    public Login()
    { }
    // ...
}

Upvotes: 2

Related Questions