Tired of adding strings ?

If you’ve ever had to write a lot of output with strings you’ve probably had to concatenate them.

In VB you used &. In Xojo you use + and more than likely Str, Format, and the newer ToString.

Eventually when you write enough code you end up with things that look like

Var Explanation as string = "Hint: If you don't save," _
  + " you will lose your work" _
  + " since your last Save."

You use the line continuation characters and spread it across multiple lines. And if you need to actually insert user generated vales you end up with code that gets increasingly hard to read

Var Explanation as string = "Hint: If you don't " _
  + action _
  + "," _
  + " you will lose your work" _
  + " since your last" _
  + action _
  + "."

If you have to add in numbers or other items that require the use of Str, Format, ToString, etc it gets cumbersome*

What I’ve become really enamoured with in many other languages is a thing called string interpolation.

In C# the previous example might look like

string Explanation = $"Hint: If you don't {action}, you will lose your work since your last {action}."

I find this quite a bit easier to read. Note the $ before the first quit – this is the indicator to the compiler this string should be interpolated. When that occurs the runtime will replace {action} with the contents of a variable in scope and insert it right there !

C# has a TON of options for dealing with strings in many different ways (and there’s a fun interactive demo to messagings around with too)

Perhaps one of the most useful is multiline string literals

string rawStringLiteralDelimiter = """"
    Raw string literals are delimited 
    by a string of at least three double quotes,
    like this: """
    """";

Console.WriteLine(rawStringLiteralDelimiter);

will output – end of line and everything

You might be wondering What if what I want to insert isn’t a string ?

That still works too !

string action = "save";
int foo = 90;

string Explanation = $"Hint: If you don't {action}, you will lose your work since your last {foo}.";

Console.WriteLine(Explanation);

would output

Its very handy and very powerful as there are all kinds of formatting options you can use in interpolated strings.

And you can get away from writing + 🙂

* I have written code where my own classes have operator_convert to automagically turn themselves into a string and that can make life a bit easier.
It just doesnt happen with built in intrinsic types in Xojo. You can’t write :

dim I as integer
dim d as date
dim s as string = "Today," + d + " we counted " + I + "twiddles"

There are some interesting StringBuilder implementations but its still much more cumbersome than interpolation in many cases.