tags:

views:

2076

answers:

9

Why does (string)int32 always throw: Cannot convert type 'int' to 'string'

public class Foo
    {   
        private int FooID;
        public Foo()
        {
            FooID = 4;
            string s = (string)FooID; //throws compile error
            string sss = FooID.ToString(); //no compile error
        }
    }
+33  A: 

Because there is no type conversion defined from Int32 to string. That's what the ToString method is for.

mquander
+1 Hit the nail on the head with that one! :-)
WestDiscGolf
+4  A: 

Int doesn't have an explicit operator to string. However, they have Int32.ToString();. Maybe you can create one with Extension methods, if you really want to.

tsilb
For what it's worth, the operation he's attempting would be an explicit operation, not an implicit operation ;)
Daniel Schaffer
+4  A: 

Because C# does not know how to convert int to string, the library (.ToString) does.

Timbo
I had to downvote for the odd terminology...library? We call them methods (or even function would be acceptable).
Mark Brackett
The library which implements .ToString.But lets not quibble about terminology.
Christopher
+9  A: 

When performing a cast operation like (string)30, you're basically telling the computer that "this object is similar enough to the object I'm casting to that I won't lose much (or any) data/functionality".

When casting a number to a string, there is a "loss" in data. A string can not perform mathematical operations, and it can't do number related things.

That is why you can do this:

int test1 = 34;
double test2 = (double)test1;

But not this:

int test1 = 34;
string test2 = (string)test1;

This example isn't perfect since (IIRC) the conversion here is implicit, however the idea is that when converting to a double, you don't lose any information. That data type can still basically act the same whether it's a double or an int. The same can't be said of an int to a string.

Casting is (usually) only allowed when you won't lose much functionality after the conversion is done.

The .ToString() method is different from casting because it's just a method that returns a string data type.

Dan Herbert
"you're ... telling the computer that "this object is similar enough to the object I'm casting to that I won't lose any data"."Using a cast you're telling the compiler that they are THE SAME and any differences should be discarded. I like your answer, but not that statement.
Oy! An explicit cast *is allowed* to lose data, and even throw. An implicit cast should not lose data, and should never throw (because it can be done automatically).
Mark Brackett
This answer seems wrong to me. For example if I do this: int i = (int)Math.PI; I end up with 3 in i an loose 0.14159265358979. Isn't this a loss of data?
Martin Brown
@Martin, how is the answer wrong? I said you won't lose "much", meaning it's possible to lose data. Of course what "much" data actually means can vary a lot, but I never said there's no loss of information.
Dan Herbert
@Dan, by your argument converting 70 to "70" would be losing information, but I think that is losing less than converting 3.141 to 3. At least with "70" you can convert it back to the exact starting point. Just my opinion though I don't mean any offence.
Martin Brown
That's true, however the idea is that either way you *are* losing something. Sometimes that loss can be undone, but not always.
Dan Herbert
+3  A: 

Int32 can't be casted to string because C# compiler doesn't know how to converter from one type to another.

Why is that, you will ask the reason is simple int32 is type integer/numerical and string is, oh well type string/characters. You may be able to convert from numerical type to another numerical type (ex. float to int, but be warned possible loss of accuracy). If all possible casts where coded in the compiler the compiler would become too slow and certainly would miss much of the possible casts created for user defined types which is a major NO NO.

So the workaround is that any object in C# has a function inherited .ToString() that knows how to handle every type because .ToString() is specifically coded for the specific type, and as you guessed by now returns a string.

After all Int32 type is some bits in memory (32 bits to be exact) and string type is another pile of bits (how many bits depends on how much has been allocated) the compiler/runtime doesn't know anything just by itself looking at that data until now. .ToString() function accesses the specific metadata needed to convert from one to the other.

+9  A: 

If you did this:

string s = (string)70;

What would you expect to be in s?

A. "70" the number written the way humans would read it.
B. "+70" the number written with a positive indicator in front.
C. "F" the character represented by ASCII code 70.
D. "\x00\x00\x00F" the four bytes of an int each separately converted to their ASCII representation.
E. "\x0000F" the int split into two sets of two bytes each representing a Unicode character.
F. "1000110" the binary representation for 70.
G. "$70" the integer converted to a currency
H. Something else.

The compiler can't tell so it makes you do it the long way.

There are two "long ways". The first is to use one of the the Convert.ToString() overloads something like this:

string s = Convert.ToString(-70, 10);

This means that it will convert the number to a string using base 10 notation. If the number is negative it displays a "-" at the start, otherwise it just shows the number. However if you convert to Binary, Octal or Hexadecimal, negative numbers are displayed in twos complement so Convert.ToString(-7, 16) becomes "ffffffba".

The other "long way" is to use ToString with a string formatter like this:

string s2 = 70.ToString("D");

The D is a formatter code and tells the ToString method how to convert to a string. Some of the interesting codes are listed below:

"D" Decimal format which is digits 0-9 with a "-" at the start if required. E.g. -70 becomes "-70".
"D8" I've shown 8 but could be any number. The same as decimal, but it pads with zeros to the required length. E.g. -70 becomes "-00000070".
"N" Thousand separators are inserted and ".00" is added at the end. E.g. -1000 becomes "-1,000.00".
"C" A currency symbol is added at the start after the "-" then it is the same as "N". E.g. Using en-Gb culture -1000 becomes "-£1,000.00".
"X" Hexadecimal format. E.g. -70 becomes "46".

Note: These formats are dependent upon the current culture settings so if you are using en-Us you will get a "$" instead of a "£" when using format code "C".

For more information on format codes see MSDN - Standard Numeric Format Strings.

Martin Brown
The answer, in my view :) Not everyone will want the string to be 70, particularly those working at the byte level with networking and so on
Chris S
This answer is misleading. A number can implicitly convert to a string (probably by adding ToString() at compile time to the object) if concatenating it with other strings and the result is predictable.
Dan Herbert
+3  A: 

Just another note: In general, if you want to do an explicit conversion like this (and I agree with many other answers here as to why it needs to be an explicit conversion) don't overlook the Convert type. It is designed for these sorts of primitive/simple type conversions.

I know that when starting in C# (and coming from C++) I found myself running into type casts that seemed like they should have worked. C++ is just a bit more liberal when it comes to this sort of thing, so in C# the designers wanted you to know when your type conversion were ambiguous or ill-advised. The Convert type then fills in the gaps by allowing you to explicitly convert and understand the side-effects.

ee
A: 

VB .net is perfectly capable of casting from an int to string... in fact so is java. Why should c# have a problem with it? Sometimes it is necessary to use a number value in calculations and then display the result in a string format. How else would you manage to display the result of a calculation in a textbox?

The responses given here make no sense. There must be a way to cast an int as a string.

Jimbo
Welcome to StackOverflow. Please be aware that this is not a discussion forum, but a question-and-answer site: if you have a question, please post it as a new question here: http://stackoverflow.com/questions/ask . Personally, I would be intrigued to learn how you have managed to persuade Java to " *cast* from an int to a string".
AakashM
A: 

I just found the answer. ToString works fine on an int variable. You just have to make sure you add the brackets.

ie...

int intMyInt=32;

string strMyString = intMyString.ToString();

Jimbo