Sobes.tech
Junior

What is string interpolation and how does it allow variables to be used inside strings?

sobes.tech AI

Answer from AI

String interpolation is syntactic sugar in C# that allows embedding variable values directly into a string literal, prefixed by the $ symbol.

How it works:

  1. The string starts with $.
  2. Variables or expressions to embed are enclosed in curly braces {} within the string.
  3. The compiler automatically converts the interpolated string into a call to string.Format.

Example:

var name = "World";
var greeting = $"Hello, {name}!"; // Embedding the variable name
var sum = 2 + 3;
var result = $"Sum result: {sum}"; // Embedding the result of the expression