Click here to Skip to main content
15,893,668 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi There,

I come from a PHP background and would like to know if there's a way to check if a variable exists, and if not create it.

Something similar as seen in the the PHP code below.
if(isset($variable)){
    echo 'variable is set';
}else{
    echo 'variable is not set';
    $variable = 'This variable is now set';
}

Currently I am getting the error "Cannot use local variable 'pricelist' before it is declared". Keep in mind this is a C# console application, not a web based app.

Regards,

What I have tried:

Online research but could not find anything unfortunately.
Posted
Updated 21-Mar-17 22:22pm

1 solution

In C# all variables must be declared before they are used:
C#
string variable = null; // <- declaration
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:
C#
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:
C#
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";
        }
    }
}
 
Share this answer
 
Comments
Zach West 22-Mar-17 4:46am    
Thanks so much for clearing that up Tomas.

Regards,
Zach

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900