In C# all variables must be declared before they are used:
string variable = null;
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
variable = "This variable is now set";
}
But the previous example is a bit silly. Let's assume you have a method and you want to test an argument:
public void Run(string variable)
{
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
}
}
In any case the variable must exist before you first use it. And C# forces you to initialize all local variables explicitly. On the other hand member fields of a class get default values assigned so this will work:
class Test
{
private string variable;
public void Run()
{
if(variable != null)
{
Console.WriteLine("variable is set");
}
else
{
Console.WriteLine("variable is not set");
variable = "This variable is now set";
}
}
}