Home > DeveloperSection > Forums > If statements in methods
Ankit Singh

Total Post:341

Points:2389
Posted on    November-13-2013 7:16 AM

 C# C# 
Ratings:


 1 Reply(s)
 650  View(s)
Rate this:

I have a variable set in C# that changes depending on which If statement is selected.

But when I try to Console.WriteLine, it tells me the variable does not exist in the current context, could someone help me with this please?

public void mood()

{

  var unhappiness = Hunger + Boredom;

  if (unhappiness < 5)

  {

    string m = "Happy";

  }

  if (unhappiness <= 5 && unhappiness <= 10)

  {

    string m = "Okay";

  }

  if (unhappiness <= 11 && unhappiness <= 15)

  {

    string m = "Frustrated";

  }

  if (unhappiness <= 16)

  {

    string m = "Mad";

  }

  Console.WriteLine(m);

}



ezra heywood
ezra heywood

Total Post:145

Points:1019
Posted on    November-13-2013 7:44 AM

Hi Ankit,

You can try this:

public void mood()

{

    var unhappiness = Hunger + Boredom;

    string m = string.Empty;

    if (unhappiness < 5)

    {

        m = "Happy";

    }

    if (unhappiness >= 6 && unhappiness <= 10)

    {

        m = "Okay";

    }

    if (unhappiness >= 11 && unhappiness <= 15)

    {

        m = "Frustrated";

    }

    if (unhappiness >= 16)

    {

        m = "Mad";

    }

    Console.WriteLine(m);

}

The problem was that m was defined inside an if statement, it scope was limited to that statement.


Don't want to miss updates? Please click the below button!

Follow MindStick