Variable Declaration in IF statement

  • Thread starter Thread starter wandering1
  • Start date Start date
W

wandering1

I would assume that the following would declare the variable someClass
and it's scope would be confined to the if statement.

if((SomeClass someClass =
this.DoesASomeClassExist(identifier))!=null){
someClass.DoSomething();
}

Is there a better more compact way to write this that I cannot think
of?
Am I getting inappropriate compiler errors(in other words should this
compile)?

Thanks,
Harlan
 
You can't declare a variable within and if statement.

And honestly, even if you could I'd advise against it. There's a fine line
between writing compact/readable code and IMHO, declaring variables in an if
statement crosses it.

For example:

string s = other = "1234";

As opposed to

s = "1234";

other = s;

Some people may miss the fact you're assigning "1234" to two different
variables in the above scenario. This just makes it harder for someone else
to read and understand your code.
 
You cannot do that in C#. You need to declare that variable outside of the if statement

Tu-Thac

----- wandering1 wrote: ----

I would assume that the following would declare the variable someClas
and it's scope would be confined to the if statement

if((SomeClass someClass
this.DoesASomeClassExist(identifier))!=null)
someClass.DoSomething()


Is there a better more compact way to write this that I cannot thin
of
Am I getting inappropriate compiler errors(in other words should thi
compile)

Thanks
Harla
 
Back
Top