Forum > Drawing variables as text

First off, this book is fantastic. I have learned quite a bit from reading it, and have enrolled in the Microsoft Dream Build Play competition. I am recommending this to all of my friends as well.

One comment I think could be included, is that I ran into trouble when trying to display a numeric variable in a DrawString command. I kept receiving the error "Cannot implicitly convert 'float' to 'string'". I found that if I set the variable to something like:

outputString = numericVariable + "";

rather than something like:

outputString = numericVariable;

it does display the numericVariable without error. I couldn't find any documentation of this in the book, so you may want to include it in the next one, which I am highly anticipating.

June 22, 2008 | Unregistered CommenterDaniel, US

Glad you like the book and are looking forward to the sequel. The problem you are having is because the C# compiler sometimes figures out what you want, and other times doesn't. It is to do with the fact that although all objects provide a method which will convert them to string (it is called ToString) the compiler doesn't always know to use it.

If an object is used in a context where strings are definitely needed (for example adding one string to another) the compiler knows what to do and does it. However, if the compiler just sees an attempt to put an object of one type (a float) into a box of another type (a string) it generates an error since this is not allowed. The proper way to do it (which is actually mentioned in the next book) is to do this:

outputString = numericVariable.ToString();

June 25, 2008 | Registered CommenterRob