c# – Declare variables outside if-else statement scope

If you declare (and initialize) a variable within an if-else statement, then that variable’s value will only exist within that if-else statement. However if you want to initialize (i.e. assign a value to) the variable within the if-else statement, but want to make the variable accessible outside the if-else scope, then you need to first declare the variable, in the highest most scope where you want to make the variable accessible, and then initialize it within the scope, here’s an example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

class Program
    {
        static void Main(string[] args)
        {

			string ContainsSeedsSentence;   // Have to declare this outside if-else statement.
            if(true)
            {
                Console.WriteLine("True statement run");
                ContainsSeedsSentence = "This fruit contains seeds.";
                //Console.WriteLine(ContainsSeedsSentence);
            }
            else
            {
                Console.WriteLine("False statement run");
                ContainsSeedsSentence = "This fruit is seedless.";
                //Console.WriteLine(ContainsSeedsSentence);
            }

            Console.WriteLine(ContainsSeedsSentence);
        }
    }