Jim41Mavs Jim41Mavs - 1 month ago 14
C# Question

C# Type conversion (string to int)

I'm currently iterating through a list of items(hotels) and I need to find out the price per night if the content editor inputs more than 1 night's price.

if (!string.IsNullOrEmpty(resource))
{
var results = JsonConvert.DeserializeObject(resource).ToString();
if (!string.IsNullOrEmpty(results))
{
var hotels = JsonConvert.DeserializeObject<ContainerHotelViewModel>(results).Hotels;

if (daysDuration > 1)
{
foreach (var hotel in hotels)
{
string convertInt = hotel.BaseRate;
int nightRate;
int.TryParse(hotel.BaseRate, out nightRate);
convertInt = nightRate / daysDuration;
}
}

return SortHotels(hotelIds, hotels);
}
}


So my understanding is that I've converted
hotel.BaseRate
from a
string
to an
int
. So it makes sense for me to divide the
hotel.BaseRate
by the
daysDuration
to get the price per night as they are both ints now. Please advise on what I'm doing wrong as my final line of code in the foreach loop is giving me the error message:


Cannot implicitly convert type int to string.

Answer
string convertInt = hotel.BaseRate;
int nightRate;
int.TryParse(hotel.BaseRate, out nightRate);
convertInt = nightRate / daysDuration;

You first declare convertInt as a string and then try to set it to response from your equation.

Remove first line and set last to this:

int convertInt = nightRate / daysDuration;