[C#] Declare assign variable in if statement

Hi all,

This is probably pretty simpel but I can’t get it to work. It isn’t even related to Unity but to C# syntax but hey, I know there are some C# guru’s here.
What I want to achieve is the following:
(this doesn’t work)

if (GameObject g = stack.Peek())
{
      g.active = true;
}

So basicly, if the stack isn’t empty return the top gameobject from the stack and asign it to ‘g’.
What does work is:

GameObject g;
if(g = menuStack.Peek())
{
      g.active = true;
}

but I think I saw something like the first piece of code somewhere and now I can’t get this out of my head :wink:

You will have to do something like

GameObject g = null;
if( (g = menuStack.Peek()) != null ) {
  g.active = true;
}

(not 100% sure that this works)

or cleaner

GameObject g = menuStack.Peek();
if( g != null ) {
  g.active = true;
}
1 Like

I found a discussion about declaring and assigning variables inside a condition here: Microsoft Q&A | Microsoft Learn.

It seems it cannot be done in C#, even though you can in other languages. It has to do with the fact that GameObject foo = null; is considered a statement, not an expression, and as such doesn’t return any value that you could use.

(Also, you live near me! Nice to know there are Unity users close-by :))

Thanks for the answers guys. Sometimes knowing multiple programming languages makes your mind buble :wink:

p.s. Funny you live so close near my company Tinus! I guess Unity is becoming more and more popular here in The Netherlands.

Hey,

You cannot declare variable in if clause, but you can assing them:

object obj;
if ((obj = function()) != null)

thing is C# conditions don’t work as C ones. In C anything that has value of 0 is “false” and everything else is “true”. In C# it has to actually be a boolean value (good thing actually).

(obj = function()) → nullable object (ok in C)
((obj = function()) != null) → boolean (ok in C#)

Ahh right! Thats where I went wrong, I actually had the C style conditions in my head.

As developers we always need to keep learning :slight_smile:

Its kinda funny, I apparently had a very bad example :sweat_smile:

GameObject g = null; 
if( (g = menuStack.Peek()) != null ) { 
  g.active = true; 
}

The problem here is: when menuStack is empty it can’t peek and returns an error, it will not asign null to g.
The code I now use is nothing special:

if (menuStack.Count > 0)
{
     GameObject g = menuStack.Peek();
     g.active = true;
}