Click here to Skip to main content
15,909,897 members
Please Sign up or sign in to vote.
1.89/5 (5 votes)
See more:
When I try condition with int variable and string variable
it gives an error

Please help me

Ajith

What I have tried:

C#
int nSet =0 ;
int nCount=0 ;
string  cPrevtag ="";

/* nCount and cPrevtag change with my method calling

if (nCount == 1 && cPrevtag = 'O')
   {
     nSet = nSet + 1;

   }
Posted
Updated 25-May-17 12:51pm
v2
Comments
[no name] 25-May-17 13:54pm    
A char is not a string. = is not the same as ==.
Member 12931315 25-May-17 14:35pm    
Thanks, but I tried result is same

Ajith

Two things wrong here:
if (nCount == 1 && cPrevtag = 'O')

1) cPrevtag is declared as a string, but your comparison is with a character - that isn;t allowed.
2) "=" is an assignment, not a comparison: and C# requires boolean results (unlike C and C++ which work with "non-zero-is-true"). The comparison operator is "=="

Try this:
if (nCount == 1 && cPrevtag == "O")
 
Share this answer
 
Comments
Member 12931315 25-May-17 14:34pm    
Hi Griff

I tried that it's still it's say operator '==' cannot be applied to operand string
is there any better way ?

Thanks in advance

Ajith
[no name] 25-May-17 14:47pm    
Then you did something wrong. What we told you was correct and does work. But since you don't like to share little things like error messages, we are left to guessing what your problem is.
OriginalGriff 25-May-17 14:50pm    
Read my code carefully: I changed the "=" to "==" *and* the 'O' to "O"
OriginalGriff 25-May-17 14:51pm    
Sorry - that wasn't meant for you - it was intended for the OP... :blush:
OriginalGriff 25-May-17 14:51pm    
Read my code carefully: I changed the "=" to "==" *and* the 'O' to "O"
There are numerous problems with your code, but this will compile. No idea if it works, since you don't show the rest of your app:

int nSet =0 ;
int nCount=0 ;
string cPrevtag ="";

/* nCount and cPrevtag change with my method calling */

if (nCount == 1 && cPrevtag == "O")
{
    nSet = nSet + 1;

}


As others have noted, you can't compare a string to a character ( single quotes indicate a character). Also, you have to use == for comparison. Finally, your comment wasn't closed */

Matt
 
Share this answer
 
Comments
Member 12931315 25-May-17 15:02pm    
Thanks Matt, I put that comment only for the question
CPallini 25-May-17 15:52pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900