- Home /
C# if If Statement is True Declare Variable
Hi everyone, how do declare a variable inside of an if statement? I want to declare a variable when a specific if statement is true. But I'm not sure how.
Answer by hiddenspring81 · Jun 01, 2013 at 12:50 AM
You cannot actually do that, but here's an alternative option. Suppose that you have a class Foo
,
Foo instance = null;
if (x == 1)
{
instance = new Foo();
}
Does that solve your problem? If not, let me know more specifically what the problem is.
So basically what I would have to do is create a variable, set it to null and in the if statement have it equal to a new variable.Does null set it so it can't be used?
The reason that you have to declare instance
before the if
statement is that you need to make sure the variable will exist, regardless of which code path the application executes at runtime. For example, if your code was
// This won't work
if (x == 1)
{
Foo instance = new Foo();
}
instance.fooBar();
Your compiler would choke, because instance
was declared inside of the if
statement. At runtime, if x
was equal to 2, then it would never assign Foo instance = new Foo()
, and the instance
variable wouldn't exist.
To make the compiler happy, you just need to declare instance
before the if
statement. That way, regardless of whether or not the if
statement is satisfied, the instance
variable will always exist. Assigning it a value of null
is just a convenient default value. Assigning a variable null
essentially means that it has no value.
Is there a way to set it so it can't be used unless the if statement is true?
Soft of. You would just need to place null-checks before you attempt to you use the variable.
Foo instance = null;
if (x == 1)
{
instance = new Foo();
}
// Check if instance has been assigned, then do stuff with it
if (instance != null)
instance.FooBar();
Don't worry about instance
"wasting" memory. Because instance
is null
, it's not consu$$anonymous$$g any memory whatsoever.