C#: Operator '!=' cannot be applied to operands of type 'object' and 'char'

  • A+
Category:Languages

I am a new learner and trying to solve a problem on the Leetcode, but there was a compile error.

public class Solution  { public bool IsValid(string s)  {     if(s.Length%2==1)     {         return false;     }     if(s.Length==0)     {         return true;     }     Stack st=new Stack();     for(int i=0;i<s.Length;i++)     {         switch(s[i])         {             case '(':             st.Push(s[i]);             break;             case'[':             st.Push(s[i]);             break;             case'{':             st.Push(s[i]);             break;             case ')':             if(st.Count==0||st.Peek()!='(')             {                 return false;             }             else             {                 st.Pop();             }             break;             case']':             if(st.Count==0||st.Peek()!='[')             {                 return false;             }             else             {                 st.Pop();             }             break;             case'}':             if(st.Count==0||st.Peek()!='}')             {                 return false;             }             else             {                 st.Pop();             }             break;         }     }     return st.Count==0; } } 

I get an error.

Line 28: Operator '!=' cannot be applied to operands of type 'object' and 'char'

Might be this one

if(st.Count==0||st.Peek()!='(')     

I know this is about datatype, but I don't know how to solve it.

I am not an English speaker so some of my English grammar might be crazy. Sorry about that, and thank you if you can help me.

 


You are getting the error because you are using a Stack without generics. Your stack is a stack of type Object.

You would need to cast the data you pop or peek from your stack to char.

example:

if(st.Count==0|| (char) st.Peek()!='(')   

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: