CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Dec 2002
    Posts
    16

    convert int to string

    I don't understand why the code further below isn't returning an error. As far as I know you can't assign the data type int to a variable of data type string unless you explicitly convert the int data type to a string. I don't believe there is any implicit conversion. So in the example below the i variable holds a number but I've been able to assign this with the "<br />" tag to the tellme variable, which is a string variable, each time through the loop, I've done this without any conversion.

    This also raises another issue, if the i variable is converted to a string then the code should fail on the second test of the loop as the i variable would no longer hold a number, it would hold a string.

    I'm totally confused here, can anyone please help.


    <script language="C#" runat="server">
    void Page_Load()
    {
    string tellme = "";
    int i = 0;

    while (i <= 9)
    {
    if (i == 6)
    break;
    tellme += i + "<br />";
    i++;
    }

    Message.Text = tellme;
    }
    </script>
    <html>
    <head>
    <title>break</title>
    </head>
    <body>
    <asp:label id="Message" runat="server" />
    </body>
    </html>

    Note I know the code itself is pretty pointless, it's just an example.

  2. #2
    Join Date
    Jan 2003
    Location
    Ohio
    Posts
    31
    I'm just learning C# myself but I think even simple data types in C# are derived from the object class which has a ToString method. So if your type is "int" and you assign it to a string you are actually assigning int.ToString() to the string.
    hiccup

  3. #3
    Join Date
    Aug 2002
    Location
    Germany, Berlin
    Posts
    60
    You are right "int.ToString();" is correct. For the other way you can use the Convert-class.

  4. #4
    Join Date
    Jan 2003
    Location
    Massachusetts
    Posts
    170

    Lightbulb Convert String to int

    I just wanted to add an example here for anyone who might be looking for this. The following code will take input as a String from the keyboard and convert it to an int:

    Code:
    static void Main(string[] args)
    {
        System.Console.Out.WriteLine("Enter a number: ");
        String strIn = System.Console.ReadLine();
        int i = (int)Convert.ChangeType(strIn, typeof(int));
    }
    jim
    I am scifi

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured