Click here to Skip to main content
16,016,678 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
Hi
can i convert a string to integer variable in C#?If so can you please tell me.I have given the port number <port>10000<port> in an xml file .I want to read this number from xml and assign to int variable so that it can be passed to the IPEndPoint() for client/server commnuication.Whatever i read from xml is retrieved as string.I tried with ConvertToInt() but still im not getting.Can you please explain me the reason?
Posted

musefan has given you the perfect answer. Just be aware that if the number can't be converted to an int you will get zero.

I have an extension method that I use when working with text/xml etc files to simplify stuff.
public static class ExtensionMethods<br />{<br />    /// <summary><br />    /// Converts a string to an integer.<br />    /// </summary><br />    /// <param name="value">The string to convert.</param><br />    /// <returns>The integer value of the string if valid; otherwise, zero.</returns><br />    public static Int32 ToInt32(this string value)<br />    {<br />        int result;<br />        Int32.TryParse(value, out result);<br />        return result;<br />    }<br />}
Now I can can just use something like
int intFromFile = stringFromFile.ToInt32();


 
Share this answer
 
int result;

int.TryParse("10000", out result);

 
Share this answer
 


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