1

I want to compare elements in a object type array with a user input. To do that I wrote the following code. There is no error in the code but I found out that object comparison does not work as I expected. How can I edit my code to compare user inputs with predefined array?

class Program
{
    static void Main(string[] args)
    {
        object[] Mathfunction = new object[] { '+','-','*','/'};
        Console.WriteLine("Enter");
        object input = Console.ReadLine();
        for(int i=0;i<4;i++)
        {
            if (Mathfunction[i] == input)
            {
                Console.WriteLine("done");
                Console.ReadLine();
            }
        }
    }
Jason Down
  • 21,731
  • 12
  • 83
  • 117
KMA
  • 211
  • 3
  • 17
  • Why not just use 4 separate `if` statements? – Scott Solmer Sep 14 '14 at 13:56
  • @Okuma.Scott, having if's would be harder to maintain and to understand. This is well explained here. http://stackoverflow.com/questions/1554180/why-is-the-if-statement-considered-evil – codea Sep 14 '14 at 14:02

4 Answers4

3

You're comparing strings to boxed chars.
Those are not going to be equal.

You should declare your variables as the actual datatypes you're using instead of object; then, the compiler will tell you what you're doing wrong so you can fix it.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
1

Is there any reason that you extremely need to convert char to object? If no, I would suggest you to convert it back to char[] and the comparison is fixed. Otherwise, when you compare two objects, it actually is comparing two references, not the (char) values. And since one object was created when you initiated the array, one is input by user, two of them will never be the same, and the comparison will never return true.

Harry Ninh
  • 16,288
  • 5
  • 60
  • 54
1

I have change my program as followa now it works as I expected.

class Program
{
    static void Main(string[] args)
    {
        object[] Mathfunction = new object[] { '+','-','*','/'};
        Console.WriteLine("Enter");
        String input = Console.ReadLine();
        for(int i=0;i<4;i++)
        {
            String str = (Mathfunction[i].ToString());
            if (String.Equals(str,input))
            {
                Console.WriteLine("done");
                Console.ReadLine();
            }
        }
    }
KMA
  • 211
  • 3
  • 17
0

try something like this , in your code the input will be in one object while you are using an array of objects to store the characters , you can do as the following :

object[] Mathfunction = new object[] { '+', '-', '*', '/' };
Console.WriteLine("Enter");
object input = Console.ReadLine();
string[] inputString = input.ToString().Split(' ');
bool isEqual = true;
for (int i = 0; i < 4; i++)
{
    if (Mathfunction[i].ToString() != inputString[i])
    {
        isEqual = false;
    }            
}
if (isEqual)
{
    Console.WriteLine("done");
    Console.ReadLine();
}
Ateeq
  • 797
  • 2
  • 9
  • 27