If Statements In C#

One of the basics of C# and an extremely useful and common piece of code, understanding If statements is vital for good developments.

In the C# programming language, the IF statement is a logical condition check. Its function is to check if a condition is true, and if so, run some specified code.

If Examples

The ELSE-IF statement can appear after an If statement, and specifies a second condition to check for once the first has been evaluated as False.

The code inside an Else-If statement runs ONLY IF the precedingIf statement is false.

Else-If Example

The ELSE statement can be attached to the end of an IF/ELSE-IF chain. Like the name implies, if all IF and ELSE-IF conditions are False, the code contained in ELSE will run.

Else Example

The use cases for any type of IF statement are numerous, and it is usually the go-to method to run code based on conditions.

There is also a way to simplify the writing of IF statements even more. It is called a Ternary Operator, and is written like so:

Use the Ternary Operator to simplify IFs

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vincent Taylor

Unity game developer / C# Programmer / Gamer. Australian (Tasmanian) indie games developer for 10+ years. Currently looking for games industry employment.