|
-
April 19th, 2003, 04:43 PM
#1
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.
-
April 19th, 2003, 09:43 PM
#2
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
-
April 21st, 2003, 10:40 AM
#3
You are right "int.ToString();" is correct. For the other way you can use the Convert-class.
-
July 30th, 2003, 02:49 PM
#4
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|