OneBite.Dev - Coding blog in a bite size

Check If Two Variable Is Not Equal In C#

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

In C# programming, comparing two variables for inequality is a common task. This article will guide you through an easy way of checking if two variables are not equal in C#.

Code Snippet: Compare Two Variables in C#

Here’s a simple code snippet illustrating this.

int num1 = 10;
int num2 = 20;
if(num1 != num2)
{
  Console.WriteLine("Numbers are not equal");
}
else
{
  Console.WriteLine("Numbers are equal");
}

Code Explanation for Compare Two Variables in C#

This code snippet is very basic, but it perfectly illustrates how to compare two variables for inequality in C#.

First, we declare and initialize two integer variables, num1 and num2, with the values of 10 and 20 respectively.

Next, we have an if statement. The if statement includes a condition to be tested - num1 != num2. The symbol != is a comparison operator in C# that checks if two values are not equivalent. If num1 and num2 are not equal, the program will execute the code within the curly brackets {} immediately following the if statement.

In this case, it prints out “Numbers are not equal”. If num1 and num2 were equal, the program would have instead executed the code within the else clause, printing out “Numbers are equal”.

That’s all there is to it! You can use this simple conditional structure to compare any two variables for inequality in C#. Remember, the != operator is not only limited to integers - it can be used to test inequality of any data type in C#.

c-sharp