zxc
zxc

Reputation: 415

Issues with comparing .ToString()

so I'm making a mock program just to get somewhat more used to c# and heres what i've got:

ConsoleKeyInfo Input;
StringBuilder sb = new StringBuilder();
const string Password = "class";

Console.Write("Input Your Password: ");
    do
    {
        Input = Console.ReadKey(true);
        sb.Append(Input.KeyChar); 
    } while (Input.Key != ConsoleKey.Enter);
    Console.WriteLine();

    if (sb.ToString() == Password)
    {
       Console.WriteLine("Correct Password!");
    }
    Console.WriteLine("You Entered: " + sb.ToString());
    Console.WriteLine("The Pass is: " + Password);

    Console.ReadLine();

But I have an issue with my if-statement when I come to compare sb.ToString() and Password. Although if you put the same thing in as Password the if-statement still doesn't become true.

Why is this?

Upvotes: 1

Views: 93

Answers (1)

Selman Genç
Selman Genç

Reputation: 101681

Because you are also adding the Enter key to StringBuilder at the end, you can just check it before adding:

do
{
    Input = Console.ReadKey(true);
    if(Input.Key != ConsoleKey.Enter)
       sb.Append(Input.KeyChar); 
} while (Input.Key != ConsoleKey.Enter);

Or instead of checking it twice you can also refactor your loop like this:

while ((Input = Console.ReadKey(true)).Key != ConsoleKey.Enter)
   sb.Append(Input.KeyChar); 

Upvotes: 5

Related Questions