Unable to use < or > with string or int

Class library usage, coding and language questions.
houseofcutler
Posts: 52
Joined: Fri Mar 21, 2014 4:22 pm

Unable to use < or > with string or int

Post by houseofcutler » Thu Jun 12, 2014 4:06 pm

Hi There,

I have a situation where I need to perform some actions based on the child index value of an element. I need to know whether the index is higher or lower than the value of a variable.

varVoice is a string (although i did convert it to an int32 while testing) the childindex is an int
while (repo.MyElement.ChildIndex > varVoice)
When I try and run this I get the following error "Operator '>' cannot be applied to operands of type 'int' and 'string'

I expected comparing numbers to each other would be simple but I cant find a way to make it work and my online searches have not presented a solution. Could someone please tell me what I am missing please..?

Many thanks

Ben

krstcs
Posts: 2683
Joined: Tue Feb 07, 2012 4:14 pm
Location: Austin, Texas, USA

Re: Unable to use < or > with string or int

Post by krstcs » Thu Jun 12, 2014 4:40 pm

You have to EXPLICITLY convert the string value to a number value in order to use arithmetic operations.

Try wrapping your string variable with "int.Parse(<your variable)".

Code: Select all

    while (repo.MyElement.ChildIndex > int.Parse(varVoice))  

There are times when .NET can do this automatically when the data types are similar (int to a long for example), but in this instance it can't because the data types are not the same. The receiving type usually has a conversion method called "Parse()" that can be used. There is also a "TryParse(in, out)" that returns a boolean (true/false) for if it was successful, and you have to supply an output parameter (the "out") that it will store the result in. This is handy for when you need to do something if the conversion was successful or not, like do addition IF the string can be converted, or throw an error to the user if not (something besides an exception, like saying "Hey, I asked for a number, silly!" instead of throwing an exception to the system... :D ).
Shortcuts usually aren't...

houseofcutler
Posts: 52
Joined: Fri Mar 21, 2014 4:22 pm

Re: Unable to use < or > with string or int

Post by houseofcutler » Thu Jun 19, 2014 3:03 pm

Thanks krstcs

I see what you mean - hadn't realised that all the variables that I pass through from the recording (and bound csv) actually come as strings even when they are a number.

This all works now - thanks