Sunday, June 23, 2024 20:26

Table of contents >> Introduction > Conversion to type String

Conversion to type String

The first kind of conversion to type string is the implicit type converting. Whenever you concatenate a string and another type which is not of type string, the .NET runtime will convert the second type to string, on the fly, in behind, without you knowing it. This is the implicit type conversion.

The next method of conversion to type string is by calling the method ToString() on the variable or value, which we used once or twice so far. This method can be used on all the data types in .NET Framework. You can even call 7.ToString() , and it would be valid, producing the string “7”.

The next example demonstrates the usage for both ways of converting to type string:

Here is the output:

conversion to type string

You can see that all three methods produce the same result – conversion to type string. The difference is that for the first line, the conversion is made automatically. As a general rule, it is considered good practice among programmers to always use explicit conversion, to avoid mistakes. In the case of implicit conversion, note that the concatenating operator (+) has the same priority with the addition sign (+). This means that you might intend to perform an addition on two numbers, then a concatenation, but might get the surprise of concatenating the values as string, instead. Consider the following example:

Aaaand… surprise! Not quite the result you would expect, isn’t it?

concatenation error

This is because when dealing with operators that have the same precedence, the order of operation is from left to right. Which means, in our case, that the first operation is to concatenate the string “The sum between 3 and 7 is ” with the number 3, which, as we learned, will be implicitly converted to a string. This will return also a string, which, as the next operation, will be concatenated with the number 7, which will also be implicitly converted, in order to successfully concatenate it. That’s why, implicit conversion can be dangerous, and you should avoid it. Instead, you can force the order of operation, as we discussed in a previous lesson. The following code will produce the correct result:

By placing 7 + 3 in parenthesis, which have a higher operator precedence than addition or concatenation, we are forcing the compiler to first perform the operation between the brackets, then the concatenation with the string. Having two numbers inside the parenthesis will perform addition, not concatenation.

The concepts explained in this lesson are also shown visually as part of the following video:

Tags: , ,

Leave a Reply

Follow the white rabbit