2 ways to compare two characters in C#

C# program to compare two user input characters:

This program will show you how to compare two user input characters in C#. It will take the characters as input from the user, compare them and print a message.

It checks if both characters are equal or not.

How to check if two characters are equal or not in C#:

In C#, we can check if two characters are equal or not in two different ways:

  • Using ’==’
  • Using ‘Char.Equals()’

Example program to compare two characters using == :

Using ==, we can simply compare two characters in C#. It returns true if both characters are equal. Else false.

using System;

public class Program
{
	public static void Main()
	{
		char c1,c2;
		
		Console.WriteLine("Enter the first character : ");
		c1 = Console.ReadLine()[0];
		
        Console.WriteLine("Enter the second character : ");
        c2 = Console.ReadLine()[0];

        if(c1 == c2)
			Console.WriteLine("Both characters are equal");
		else
			Console.WriteLine("Characters are not equal");
	}
}

In this program, We are asking the user to enter the first and the second character. The characters are stored in c1 and c2 variables.

Using == operator, it checks if both characters are equal or not. Based on its result, it prints one message to the user.

It will give output as like below:

Enter the first character : 
a
Enter the second character : 
b
Characters are not equal

Enter the first character : 
a
Enter the second character : 
a
Both characters are equal

Example program to compare two characters using Char.Equals:

Char.Equals is defined as below:

public bool Equals(char c)

We can use this method with a character and pass another character to compare. Based on the boolean value it returns, we can say both characters are equal or not.

Let’s take a look at the below program:

using System;

public class Program
{
	public static void Main()
	{
		char c1,c2;
		
		Console.WriteLine("Enter the first character : ");
		c1 = Console.ReadLine()[0];
		
        Console.WriteLine("Enter the second character : ");
        c2 = Console.ReadLine()[0];

        if(c1.Equals(c2))
			Console.WriteLine("Both characters are equal");
		else
			Console.WriteLine("Characters are not equal");
	}
}

It will give output similar to the above one.

You might also like: