I'm having a function which receives string parameters and convert them to integers.
For safe conversion int.TryParse() is used.
public IEnumerable<object> ReportView(string param1, string param2)
{
int storeId = int.TryParse(param1, out storeId) ? storeId : 0;
int titleId = int.TryParse(param2, out titleId) ? titleId : 0;
IEnumerable<object> detailView = new Report().GetData(storeId, titleId);
return detailView;
}
Function call ReportView(“2”,”4”)--> int.Tryparse successfully parsing the numbers
Function call ReportView(“2.00”,”4.00”) --> int.TryParse fails to parse the numbers
Why? Any idea?
@Update
Sorry guys, my concept was wrong. I'm new to c#, I thought Int.TryParse() would return integral part and ignore the decimals. But it won't, even Convert.ToInt32("string")
Thanks to all.
TryParse is a static data conversion method that allows to convert a string value to a corresponding 32-bit signed integer value. It returns a Boolean True value for successful conversion and False in case of failed conversion.
TryParse(String, NumberStyles, IFormatProvider, Int32) Converts the string representation of a number in a specified style and culture-specific format to its 32-bit signed integer equivalent. A return value indicates whether the conversion succeeded.
6 Answers. Show activity on this post. No, TryParse returns true or false to indicate success. The value of the out parameter is used for the parsed value, or 0 on failure.
TryParse is . NET C# method that allows you to try and parse a string into a specified type. It returns a boolean value indicating whether the conversion was successful or not. If conversion succeeded, the method will return true and the converted value will be assigned to the output parameter.
public IEnumerable<object> ReportView(string param1, string param2)
{
decimal tmp;
int storeId = decimal.TryParse(param1, out tmp) ? (int)tmp : 0;
int titleId = decimal.TryParse(param2, out tmp) ? (int)tmp : 0;
IEnumerable<object> detailView = new Report().GetData(storeId, titleId);
return detailView;
}
The above will work with Integer or Decimal strings. Mind you that strings of the form "2.123" will result in the Integer value of 2 being returned.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With