C# If And Tutorial – Complete Guide

Welcome to this interactive tutorial on the powerful “if and” statement in C#! In this tutorial, we will delve deeper into the world of conditional programming constructs. By the end of this guide, you will understand the essence of the “if and” statement in C# and how to utilize it in your programming journey.

What is the C# “if and” statement?

The C# “if and” statement is a fundamental element of conditional logic in programming. It allows us to instruct the program to perform certain actions only if specific conditions are met. This is achieved by combining multiple conditions using the logical AND operator (&&).

Why is it important to learn about the “if and” statement?

This concept forms the backbone of decision-making in coding. The “if and” statement is invaluable in creating dynamic and user-responsive applications. As we explore more, we will demonstrate its effectiveness with some engaging and relatable examples based on game mechanics.

What can you accomplish with the “if and” statement?

From creating responsive game characters to implementing complex game rules and functionalities, the possibilities with the “if and” statement are endless. Without the “if and” statement, your program would behave the same every time it runs, which is not very ideal, especially in the gaming world where dynamism and engagement are key.

Now, let’s get our hands dirty by experimenting with practical examples.

CTA Small Image

The Basics of “if and” statements in C#

The basic structure of an “if and” statement is quite straightforward. We start with the keyword ‘if’, followed by the condition, specified within parentheses. The commands to be executed if the condition is met are enclosed within curly braces {} immediately after the conditional statement.

Here’s a simple example:

int level = 10;
int lives = 5;

if (level > 5 && lives > 0) {
    Console.WriteLine("You have passed the level!");

In this code, the message “You have passed the level!” will only be displayed if the player’s level is greater than 5 AND the player is still alive (lives > 0). Both conditions must be met for the statement to be true.

Using “if and” Statements with User Input

We can use the “if and” statement to make programs more responsive to user input. Consider the following example:

Console.Write("Enter your age: ");
int age = Int32.Parse(Console.ReadLine());

Console.Write("Do you have a valid driver's license? (yes/no): ");
string license = Console.ReadLine();

if (age >= 18 && license == "yes") {
    Console.WriteLine("You are eligible to rent a car!");

In this snippet, we request the user’s age and whether they have a valid driver’s license. They are only eligible to rent a car if they are 18 years or older AND they have a valid driver’s license.

Nested “if and” Statements

We can also nest “if and” statements for more complex decision-making. Assuming we are developing a game where a player can enter a dangerous zone, only if they are level 10 or higher and have more than 50 health points. Optionally, they can bypass the level restriction with a special pass.

int playerLevel = 9;
int playerHealth = 60;
bool hasPass = true;

if((playerLevel >= 10 && playerHealth > 50) || (hasPass && playerHealth > 50)) {
    Console.WriteLine("You may enter the dangerous zone!");

Note: The usage of parentheses is essential in this example to correctly reflect the order of the conditions.

“Else If” and Multiple Conditions

It is possible to test for several conditions sequentially using “else if”. It is particularly useful when working on scenarios that are multiphase or tier-based.

For a tier-based game rewards system, consider the following example:

int playerScore = 1200;

if (playerScore >= 2000) {
    Console.WriteLine("You've earned a gold trophy!");
} else if (playerScore >= 1500 && playerScore = 1000 && playerScore < 1500) {
    Console.WriteLine("You've earned a bronze trophy!");
} else {
    Console.WriteLine("No trophy earned, keep trying!");

In the above code, different statements will be executed based on the player’s score.

Compound Statements with “if and”

Multiple conditional statements can be compounded using logical AND (&&).

Let’s illustrate this with a puzzle game scenario, where opening a mystery box requires a combination of specific items and triggered events.

// These variables represent items/events that may or may not be triggered 
bool hasKey = true; 
bool magicalGlyphActivated = false; 
bool understandsAncientLanguage = true;

if (hasKey && understandsAncientLanguage && !magicalGlyphActivated) {
    Console.WriteLine("You successfully opened the mystery box!");
} else {
    Console.WriteLine("Fail to open the mystery box.");

The “if and” statement checks for the possession of the key, the understanding of ancient language, and the status of a magical glyph. The box can only be opened if all conditions are satisfied.

The Importance of Order in “if and” Statements

The order of conditions in “if and” statements can affect your program’s logic and performance. C# evaluates the conditions from left to right and stops as soon as one condition is false. This is known as short-circuit evaluation.

Consider this example:

int lives = 0;

if (lives > 0 && (100/lives) > 10) {
    Console.WriteLine("You are doing great!");

If the order of conditions was reversed, the program would attempt to divide by zero if lives was 0, resulting in an exception. However, with the conditions in the provided order, the program will never make it to the division operation if lives is 0 because the first condition (lives > 0) will short-circuit the evaluation.

Learning to effectively use “if and” statements can significantly enhance your programming skills, especially in developing game logic and functionalities. We hope this informative guide provides a solid foundation for you to explore the boundless realm of conditional programming with C#!

Applying “if and” Statements in Game Developing

Let’s further illustrate the use of “if and” statements with some more in-depth examples from game development.

1. Controlling Game Difficulty

Suppose you are developing a game where the difficulty is adjustable. Depending on certain conditionalties such as the player’s level and score, you may want to increase or decrease the game’s difficulty:

int playerLevel = 15;
int playerScore = 2500;

if (playerLevel > 10 && playerScore > 2000) {
    Console.WriteLine("Increasing game difficulty.");

In the above example, the game’s difficulty will be increased if the player’s level is greater than 10 and their score is over 2000.

2. Implementing Interactive Game Elements

Let’s consider that we are creating an RPG (Role-Playing Game), where the player can interact with certain non-player characters (NPCs) based on specific conditions:

bool hasMysteriousAmulet = true;
bool foundAncientRelic = false;

if (hasMysteriousAmulet && !foundAncientRelic) {
    Console.WriteLine("The wise old man speaks to you.");

In this case, the NPC (the wise old man) will only interact with the player if they have the mysterious amulet but have not found the ancient relic.

3. Enabling Achievements

Another great use of “if and” statements in game development is for unlocking achievements. Based on the player’s actions or status, we can grant them special achievements:

bool defeatedDragon = true;
bool rescuedPrincess = true;

if (defeatedDragon && rescuedPrincess) {
    Console.WriteLine("Achievement Unlocked: Hero of the Land!");

This code will unlock the “Hero of the Land” achievement, only if the player has defeated the dragon and rescued the princess.

4. Granting Item Upgrades

In RPGs, players often need to complete tasks or quests to receive item upgrades. “If and” statements can be instrumental in checking if the requirements are fulfilled:

int numberOfGoblinTeethCollected = 30;
bool hasFavorOfTheBlacksmith = true;

if (numberOfGoblinTeethCollected >= 20 && hasFavorOfTheBlacksmith) {
    Console.WriteLine("Your sword has been upgraded to a Goblin Slayer!");

In this example, the player’s sword will be upgraded to a “Goblin Slayer” if they’ve collected at least 20 goblin teeth and gained the favor of the blacksmith.

5. Managing Cooldowns

Controlling the cooldown period for power-ups or skills is crucial in many games. Let’s look at a scenario where a player can only use a special move if both its cooldown has completed and the player has enough energy:

bool specialMoveIsReady = true;
int playerEnergy = 80;

if (specialMoveIsReady && playerEnergy >= 50) {
    Console.WriteLine("You unleash the special move!")

From controlling game difficulty to managing cooldowns, the applications of “if and” statements in game development are indeed endless. We hope that these examples provide you with some inspiration to create more engaging, challenging, and dynamic games.

Now that you’ve thoroughly explored the “if and” statements in C#, you might be wondering how to further extend your learning and continue on your coding journey. This fundamental programming concept is only a small part of a much bigger picture in game development.

We at Zenva strongly believe in creating the pathway for you to advance from beginner to professional, with over 250 thoroughly supported courses in programming, game development, AI, and many more. To delve further into the world of game development specifically, we would like to recommend you our comprehensive collection of courses named Unity Game Development Mini-Degree. It is a complete package providing knowledge on a wide array of topics, from underpinning game mechanics to generating cinematic cutscenes and audio effects. This Mini-Degree is suitable for both beginners and experienced developers aiming to master Unity, a widely-used game engine preferred by game developers around the globe. All courses are designed to be flexible, allowing you to learn at your own pace, accompanied by swift challenges and in-course quizzes to reinforce your understanding.

If you’re interested in exploring more options, Zenva also offers a broader collection of courses, accessible through our Unity platform. Whether you’ve just begun to grasp the basics or are aiming to perfect your developed skills, Zenva is committed to accompanying you every step of the way. Keep coding, keep experimenting and always stay curious!


In the dynamic realm of game development, the “if and” statement proves to be a powerful tool. From crafting complex game rules to creating immersive and responsive gaming environments – its scope is truly infinite. Having mastered this concept, you’re undoubtedly more equipped and confident to build your unique gaming experiences!

We at Zenva are committed to supporting you in every step of your learning journey. Whether you’re a beginner dabbling in the basics or a seasoned professional seeking advanced concepts, we’d highly recommend exploring our comprehensive Unity Game Development Mini-Degree. Tailored to your learning preferences and schedule, you’ll find all the resources you need to transform your game ideas into reality. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.