Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

C#

Liam Andersson
Liam Andersson
1,396 Points

I have trouble with public strings | C#

Hey! I would like to take the definition of a string to another class. By that I mean:

Taking the public string password; to the class Username. I've tried some things but it didnt work..


using System;

namespace Project {

public class Password {

   public string password;                    //this one
    public static void Main() {
        Password pass = new Password();

        Console.WriteLine("Please write a new password!");
        pass.password = Console.ReadLine();

        Console.WriteLine("Are you sure you want to change your password to: " + pass.password + "? (Yes/No)");
        string input = Console.ReadLine();

        if(input.ToLower() == "yes") 
        {
            Console.WriteLine("Your password has been changed to " + pass.password + "!");
            Console.WriteLine("Press any key to continue..");
            Console.ReadKey();
            Console.Clear();
            Username.Name ();

        }
        else if(input.ToLower() == "no")
        {
        Console.WriteLine(pass.password + " will not be saved as your password");
        Console.WriteLine("Press any key to restart");
        Console.ReadKey();
        Console.Clear();
        Main();
        //System.Environment.Exit(0);

        }

        else 
        {
        Console.WriteLine("ERROR! Press any key to restart");
        Console.ReadKey();
        Console.Clear();
        Main ();
        }
    }




}
class Username                  //to use it's value down here
{
    public static void Name () 
    {
     Password result_password = new Password();
     Console.WriteLine(result_password.password);
     Console.ReadKey();

    }
}

}

1 Answer

Erik Gabor
Erik Gabor
6,427 Points

You can define a string password parameter for the Name method. Or for any method you choose. Something like this:

class Username                  
{
    public static void Name (string password) 
    {

     /// We are doing something with the password

    }
}

You can define a string in the block or use with the keyword this the member of the current class. And I think It would have been nicer in your program to use while(true) loop with break and continue than calling repeatedly Main.