Click here to Skip to main content
15,312,347 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
See more:
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?

int result;

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

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 />    /// <span class="code-SummaryComment"><summary></span><br />    /// Converts a string to an integer.<br />    /// <span class="code-SummaryComment"></summary></span><br />    /// <span class="code-SummaryComment"><param name="value">The string to convert.</param></span><br />    /// <span class="code-SummaryComment"><returns>The integer value of the string if valid; otherwise, zero.</returns></span><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();


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