C# Controlling Case Sensitivity when comparing two characters

Problem:
You need to compare two characters for equality, but you need the flexibility of performing a cese-sensitive or case-insensitive comarison.
 
Solution:
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication1
{
    class CharEqual
    {
        public static bool IsCharEqual(char firstChar, char secondChar)
        {
            return (IsCharEqual(firstChar, secondChar, false));
        }
        public static bool IsCharEqual(char firstChar, char secondChar, bool caseSensitiveCompare)
        {
            if (caseSensitiveCompare)
            {
                return (firstChar.Equals(secondChar));
            }
            else
            {
                return (char.ToUpper(firstChar).Equals(char.ToUpper(secondChar)));
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            char firstChar = ‘y’;
            char secondChar = ‘Y’;
                       
            //CharEqual mc = new CharEqual();
            if (CharEqual.IsCharEqual(firstChar, secondChar, true))
            {
                Console.WriteLine("{0} = {1}", firstChar, secondChar);
            }
            else
            {
                Console.WriteLine("{0} != {1}", firstChar, secondChar);
            }
            Console.ReadLine();
        }
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s