Menu

Explaining Ternary Operators

So, lately I am working in monogame and I stumbled across something I have used in the past, but I never really understood it. I am sure this is the case for many programmers (Especially my age and younger). 

It is the Ternary Operator. 

It isn't that difficult to understand, but it is hardly ever used! Hopefully I can shed a little light on the subject.

So, in programming we all know you have conditional statements like a switch case or an if/else block, Ternary Operators sorta fall in that category. Here is an example of one (c#):

get
{
return sprite == null ? Vector2.Zero : new Vector2(sprite.Width, sprite.Height);
}

Sounds Scary, huh?

Well it really isn't. Isn't much different from your regular if/else block. Both are a conditional statement that resolves based on a Boolean value. Ternary Operators just look scary. What if we just made them output strings?

 

var result = 2 < 3 ? "True" : "False";

Which one would resolve?

Well, of course it would be "True". They are easy as that! They evaluate Right to Left based on the logic in the conditional. 

So what is happening in my game code above? It says sprite == null right?
Basically what I am doing is checking if my sprite is null first, and if it is not setting a position for it. If it is not null, I set the sprite's position.

 

Hopefully that makes them a little more clear! They are a very valuable tool in your arsenal if you can use them.

Thanks for reading!

aribaa

Programmer, game designer, and gamer! I own and moderate the site, as well as post some of my creations. :3

aribaa

Programmer, game designer, and gamer! I own and moderate the site, as well as post some of my creations. :3

Like Us on Facebook!

Video of the day

Dragon Quest Builders Switch!