lundi 25 mars 2019

What is the difference when if statement has {} and when if statement does not have {}?

I'm practicing with Xamarin forms and I was doing a simple exercise and when I run the program the button did not work. I checked my code and I decided to remove the { } from an if statement and then the button started working. I have noticed this behavior from time to time.

Why does this happen? What is the difference? I have always been thought that every code block must be inside a {}.

Could anyone help me explain so may I understand? Below the Xamarin code with its C# code behind.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage Padding="20" xmlns="http://xamarin.com/schemas/2014/forms"
        xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
        xmlns:local="clr-namespace:T_3000_QuotePageXMAL"
        x:Class="T_3000_QuotePageXMAL.MainPage">

<StackLayout>
    <Button Text="Next" Clicked="Button_Clicked"></Button>
    <Label Text="{Binding Source={x:Reference Slider}, Path=Value, 
     StringFormat='Font Size:{0:N0}'}"></Label>
    <Slider x:Name="Slider" Maximum="50" Minimum="16"></Slider>
    <Label x:Name="currentQuote"
           FontSize="{Binding Source={x:Reference Slider},Path=Value}"> 
    </Label>
</StackLayout>

</ContentPage>

Now, the C# code behind:

 public partial class MainPage : ContentPage
 {
    int index = 0;
    public string[] quotes = new string[]
 {
    "Life is like riding a bicycle. To keep your balance, you must 
     keep moving.",
    "You can't blame gravity for falling in love.",
    "Look deep into nature, and then you will understand everything 
     better."
  } ;
  public MainPage()
  {
    InitializeComponent();
    currentQuote.Text = quotes[index];

  }

  private void Button_Clicked(object sender, EventArgs e)
  {
    index++;
    if (index>= quotes.Length)
    {  // when I remove the { } from this block the button works 
        index = 0;
        currentQuote.Text = quotes[index];

    } // but when they are inserted , the button does not work
  }

}

See the comments on the code block of the if statement.

Aucun commentaire:

Enregistrer un commentaire