OneBite.Dev - Coding blog in a bite size

Check If Two Variable Not Equal In C#

Code snippet for how to Check If Two Variable Not Equal In C# with sample and detail explanation

In software development, there are a number of instances where we need to compare variables. Today, we’ll examine how to check if two variables are not equal in the C# programming language.

Code snippet: Checking If Two Variables Are Not Equal In C#

int var1 = 100;
int var2 = 200;

if (var1 != var2)
{
    Console.WriteLine("var1 and var2 are not equal");
}
else
{
    Console.WriteLine("var1 and var2 are equal");
}

Code Explanation for Checking If Two Variables Are Not Equal In C#

In the above code snippet, the ‘!=’ operator is used to test if two variables are not equal. Here, we are comparing two variables: var1 and var2, which are numbers (integers to be more precise).

We start by initializing two integer variables var1 and var2 with values of 100 and 200 respectively.

Following this, we have an if statement in which the condition checks if var1 is not equal to var2. This is done using the ‘!=’ operator. If this is the case (that the values are not equal), then var1 and var2 are not equal gets printed to the console.

However, if var1 and var2 are equal, the code following the else keyword is executed. Thus, var1 and var2 are equal gets printed.

In this particular example, because var1 and var2 are indeed not equal to each other, the output of this code would be var1 and var2 are not equal. Hence, the ‘!=’ operator serves as a useful tool for comparing two variables in C#, especially when testing for inequality.

And that’s it! You’ve successfully learned how to check if two variables are not equal in C#. Payload this knowledge into your C# programming and let your codes flex their intelligence!

c-sharp