Click here to Skip to main content
15,886,798 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
How do OI convert string value to integer in C#?

I need to convert IDs here to integer.

string[] IDs = hdnFldSelectedValues.Value.Trim().Split('|');
Posted
Updated 2-Feb-11 19:13pm
v3

This is how:

C#
string[] IDs = hdnFldSelectedValues.Trim().Split('|');
int[] Values = new int[IDs.Length];
for(int index = 0; index < Values.Length; index++)
    Values[index] = int.Parse(IDs[index]);


This code will throw exception on first invalid numeric format of out of range. If invalid format should be converted to a special value indicating error (not recommended) use int.TryParse:

C#
string[] IDs = hdnFldSelectedValues.Trim().Split('|');
int[] Values = new int[IDs.Length];
for(int index = 0; index < Values.Length; index++) {
    int value;
    if (!int.TryParse(IDs[index], out value))
        value = -1;
    Values[index] = value;
} //loop index


In last example, failure to parse a string will be converted to -1.
Again, throwing exception is better.

—SA
 
Share this answer
 
v4
C#
List<int> list = new List<int>();
foreach (string id in IDs)
{
    int result;
    if (int.TryParse(id, out result))
        list.Add(result);
}
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 3-Feb-11 1:09am    
There is a bug: what happens if TryParse returns false? The variable result is not assigned.
Unfortunately, List is a huge overkill for such a simple task, the array is more then enough. TryParse suggests ill practice, should be advised better variant with exception. OP would not get explanation what happens with invalid numeric format. Sorry, pretty bad answer. I normally don't accept such quality of code.
Your arguments are welcome.
--SA
Chris Maunder 3-Feb-11 1:15am    
An out paramter will always be assigned a value. Even so, I follow the pattern of

if (!int.TryParse(..., out variable))
variable = 0;
Sergey Alexandrovich Kryukov 3-Feb-11 1:28am    
You're right. In this code there is not control over the int value used when TryParse fails.
"Always" means: in the case of failure variable = default(int), which is not always what can be indended.
--SA
Sergey Alexandrovich Kryukov 3-Feb-11 1:34am    
Thank you Chris, I fixed a bug.
--SA

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