Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Convert String to int32

0 views
Skip to first unread message

René Paschold

unread,
Mar 13, 2003, 10:21:02 AM3/13/03
to
Hello,

i have tried follow line:

int z = (int) TextBox1.Text);
But this one dosen´t work!

I have use the convert Class:
int z = Convert.ToInt32(textBox1.Text);
It works.

Can you tell me why the first not works?
I have thought thats the same than the second
line?

Cheers
Rene

Jon Skeet

unread,
Mar 13, 2003, 10:24:52 AM3/13/03
to
René Paschold <mai...@rpweb.info> wrote:
> i have tried follow line:
>
> int z = (int) TextBox1.Text);
> But this one dosen´t work!

No, it wouldn't.



> I have use the convert Class:
> int z = Convert.ToInt32(textBox1.Text);
> It works.
>
> Can you tell me why the first not works?
> I have thought thats the same than the second
> line?

No - a cast of object/value X to type Y will only work if:

o The actual type of X is Y or a compatible type
o There is an explict conversion of the *declared* type of X to type Y
o There is an implicit conversion of the *declared* type of X to type Y

--
Jon Skeet - <sk...@pobox.com>
http://www.pobox.com/~skeet/
If replying to the group, please do not mail me too

James

unread,
Mar 13, 2003, 11:22:42 AM3/13/03
to

"René Paschold" <mai...@rpweb.info> wrote in message
news:b4q7fe$2369k5$1...@ID-96132.news.dfncis.de...

you cannot explicitly cast objects to value types so conversion routines are
required


Jon Skeet

unread,
Mar 13, 2003, 12:05:10 PM3/13/03
to
James <ja...@jenkins2040NOSPAM.freeserve.co.uk> wrote:
> you cannot explicitly cast objects to value types so conversion routines are
> required

There's nothing special about value types here. It's perfectly easy to
write a class for objects which *can* be cast to int:

using System;

public class Test
{
public static explicit operator int(Test t)
{
return 5;
}

public static void Main()
{
int x = (int) new Test();
Console.WriteLine (x);
}
}

The reason the cast fails in the original case is that there is no
conversion operator available for String->int.

Bob Powell

unread,
Mar 13, 2003, 12:17:12 PM3/13/03
to
If you want to convert the string representation of a number to an integer
value you can use int.Parse(string)

--

Check out the GDI+ FAQ
http://www.bobpowell.net/gdiplus_faq.htm

"René Paschold" <mai...@rpweb.info> wrote in message
news:b4q7fe$2369k5$1...@ID-96132.news.dfncis.de...

Ralph Gerbig [489473]

unread,
Mar 16, 2003, 6:10:27 AM3/16/03
to
string number = 12;
int intnumber;
double dnumber;

if you want to convert string -> int
intnumber = int.Parse(number);

string -> double
dnumber = double.Parse(number);

anything to string
intnumber.ToString();
dnumber.ToString();

--
Thanks

Ralph Gerbig

www.ralphgerbig.de.vu

mail-to: samu...@web.de
"René Paschold" <mai...@rpweb.info> schrieb im Newsbeitrag
news:b4q7fe$2369k5$1...@ID-96132.news.dfncis.de...

0 new messages