beginner troubles with if statement

I am trying to get the if statement in C# to check if my name is written in the name string

string navn = " ";
Console.WriteLine("skriv dit navn her: ");
navn = Console.ReadLine();
if (navn = "jannik");

But it won't do what I tell it to. If anyone would be so kind as to enlighten me about what I am doing wrong here I would be very glad :)

Upvotes: 0

Views: 73

Answers (2)

Matti Virkkunen
Matti Virkkunen

Reputation: 65126

Use == to compare values. = is only for setting values.

Also, putting a semicolon (;) immediately after an if statement makes the if statement do nothing. You sure you didn't mean to put something else in there?

Upvotes: 5

Habib
Habib

Reputation: 223217

if (navn = "jannik");

You have a semicolon at the end of your if statement. That (;) is a valid statement and if statement will just act on that. You need to do:

if (navn == "jannik")
{
 Console.Write("MyName");
}

Also for comparing equality, you need == not a single =

You can also look at String.Equals Method (String, String, StringComparison) for comparison with ignore case.

if (navn.Equals("jannik", StringComparison.InvariantCultureIgnoreCase))
{
    //My Name
}
else
{
    //Some other name
}

Upvotes: 4

Related Questions