String interpolation - CSharp Language Basics

CSharp examples for Language Basics:string

Introduction

A string preceded with the $ character is called an interpolated string.

Interpolated strings can include expressions inside braces:

Demo Code

using System;//w ww .ja  va2s .  co  m
class Test
{
   static void Main(){
      int x = 4;
      Console.Write ($"A square has {x} sides");  // Prints: A square has 4 sides
      string s = $"255 in hex is {byte.MaxValue:X2}";  // X2 = 2-digit Hexadecimal
      Console.WriteLine (s);
   }
}

Result

Interpolated strings must complete on a single line, unless you also specify the verbatim string operator.

$ operator must come before @:

Demo Code

using System;//from   w  ww. j  a va  2  s  . c o  m
class Test
{
static void Main(){
     int x = 2;
     string s = $@"this spans {
     x} lines";

     Console.WriteLine (s);
}
}

Result

To include a brace literal in an interpolated string, repeat the desired brace character.


Related Tutorials