Share via


Small Basic Tip: TextWindow.WriteLine - Concatenation of Text with a Number or Expression

Scenarios

Executing: TextWindow.WriteLine("1 + 1 = " + 1 + 1)

Results in: 1 + 1 = 11

Executing: TextWindow.WriteLine(1 + 1 + " = 1 + 1")

Results in: 2 = 1 + 1

Overview

In the first example, Small Basic first sees the string "1 + 1 = ". It next sees a + and then the number 1. Small Basic knows how to add a number to a number and concatenate a string with another string but what does it do when it has a mix of a number and a string? When there is a mix of a number and a string, Small Basic converts the number to a string and then concatenates it with the other string. So the number 1 becomes the string "1" which is concatenated to the first string "1 + 1 = ". Small Basic now has the string "1 + 1 = 1". But we're not finished! We still have the + 1 part yet to process. Small Basic now takes the string "1 + 1 = 1" and the number 1 and combines them in the same way. The 1 is converted into a string and concatenated with the string "1 + 1 = 1" resulting in the string "1 + 1 = 11".

In the second example, Small Basic first sees the number 1. It next sees the + and the next number 1. So it's number plus number which is a math operation. The operation is performed with the result being the number 2. Small Basic continues on. It sees another plus sign but then it sees the string " = 1 + 1", not another number. Since there is a number and a string, Small Basic converts the number to a string and then concatenates it with the other string. The result is the string "2 = 1 + 1"

If you want Small Basic to output "1 + 1 = 2", you tell it:

TextWindow.Write("1 + 1 = ")
TextWindow.WriteLine(1 + 1)

to get

1 + 1 = 2

Definitions

Concatenate - A computer term meaning to combine data. Thus the concatenation of the strings "Hello " and "World!" result in the string "Hello World!".

Expression - Numbers and/or variables combined mathematically into a single number.

String - A series of none or more characters that can be numbers, letters, or special characters. A no character string is represented as "".

Reference

This article originally came from the Small Basic wiki.