Click here to Skip to main content
15,886,258 members
Articles / General Programming / String
Tip/Trick

String Interpolation: A New Feature of C# 6.0

Rate me:
Please Sign up or sign in to vote.
4.61/5 (10 votes)
26 Apr 2015CPOL2 min read 27.6K   70   13   6
In this tip, you will learn about the new features of C# 6.0 String Interpolation.

Introduction

On November 12, 2014, the day of the Visual Studio Connect() event, Microsoft announced Visual Studio 2015 preview with many new and exciting features for developers for testing purposes. Microsoft announced the new version of C#, C# 6.0, that came with many improvements and new features. One of the newly introduced features of C# 6.0 is String Interpolation.

What is String Interpolation

String Interpolation is another cool feature that helps you to manage string formatting easily. During the development period, formatting the string values is very common. While this is common, it may lead to errors because everytime we need to specify the placeholder for each item and then map them with the object values. String Interpolation lets you format strings in an easier manner that is regularly used to show the various records to the user. Earlier, we either used the "+" symbol or the string.Format method to format and organize various strings that now became the old way to do string concatenation. String interpolation replaces the need for string.Format(...) by using escaped curly braces, \{...} , inside strings. With the release of C# 6.0, we can rewrite the strings and can put expressions directly in the string literal to show the values, we can also specify a space before and after the string and can also add conditions to the string.

Example 1

In the following code snippet, we are using a string.Format() function that is a little complex, we need to put the numeric place holders {n} and based on the number, we need to set the variables.

C#
var message = string.Format("Book Name :{0} Price :{1}", name, price);  

String Interpolation will help developers to use the actual variables as placeholders. Developers can directly use the actual variables as placeholders using String Interpolation, that can be looked at as an improvement. Therefore, the preceding code snippet can be re-written as:

C#
var message = "Book Name :\{name} Price :\{price}";

Example 2

C#
public static void Main(string[] args)  
{  
    int a = 5, b = 10;  
    Console.WriteLine(" The value A is \{a} while B is \{b}");  
    Console.ReadKey();  
}  

Example 3

C#
public static void Main(string[] args)  
{  
    string value1 = "Abhishek";  
    string value2 = "Arora";  
    string stringValue1 = string.Format("{0} {1}", value1, value2);     // With string.Format  
    Console.WriteLine(stringValue1);  
    string stringValue2 = "\{value1} \{value2}";      // With String Interpolation  
    Console.WriteLine(stringValue2);  
}  

Demo Application using Visual Studio 2013

C#
using System;  
using System.Text;  
	  
namespace CSharpFeatures  
{  
    class StringInterpolation  
    {  
        public string Name { get; set; }  
        public string Location { get; set; }  
        public string Age { get; set; }  
        public string Email { get; set; }  
        static void Main(string[] args)  
        {  
            StringInterpolation s = new StringInterpolation();  
            s.Name = "Abhishek Arora";  
            s.Location = "Ghaziabad";  
            s.Age = "23";  
            s.Email = "abhishek.arora22@gmail.com";  
            Console.WriteLine("\n -- Old way of string concatenation using '+' Operator --");  
            Console.WriteLine(" My Name is " + s.Name + ". 
            I am from " + s.Location + ". I am " + s.Age + " years old. 
            You can\n contact me at " + s.Email);  
            Console.WriteLine("\n\n -- Old way of string concatenation using 
					String.Format Method --");  
            Console.WriteLine(string.Format(" My Name is {0}. I am from {1}. 
            I am {2} years old. You can\n contact me at {3} ", s.Name, 
					s.Location, s.Age, s.Email));  
            Console.ReadKey();  
        }  
    }  
}  

Demo Application using Visual Studio 2015 Preview

C#
using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Threading.Tasks;  
	  
namespace CSharpFeatures  
{  
    class StringInterpolation  
    {  
        public string Name { get; set; }  
        public string Location { get; set; }  
        public string Age { get; set; }  
        public string Email { get; set; }  
        static void Main(string[] args)  
        {   
            StringInterpolation s = new StringInterpolation();  
            s.Name = "Abhishek Arora";  
            s.Location = "Ghaziabad";  
            s.Age = "23";  
            s.Email = "abhishek.arora22@gmail.om";  
            Console.WriteLine("\n -- using String Interpolation Method 
				with VS 2015 preview --");  
            Console.WriteLine("\n My name is \{s.Name}. I am from \{s.Location}. 
            I am \{s.Age} years old. You can\n contact me at \ {s.Email}");  
            Console.WriteLine("\n\n -- Condition Checking -- ");  
            int totalamount = 2500;  
            Console.WriteLine("\n Congrats \{s.Name} \{totalamount == 2500 ? 
            "you are eligible for 10% discount!" : " No Discount"}");  
            Console.ReadKey();  
        }  
    }  
}  

Summary

In this tip, we learned how to use String Interpolation without the use of string.Format. I hope you liked this new feature of C# 6.0 introduced by Microsoft. Don't forget to read my other articles on the series "A new feature of C# 6.0". Share your opinion about this feature and how you will use it in your project? Your comments are most welcome.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Tester / Quality Assurance
India India
Hello this is Abhishek working as a Software Test Engineer

Comments and Discussions

 
Questionwhy they name that "interpolation"? Pin
Mr.PoorEnglish8-Oct-15 4:42
Mr.PoorEnglish8-Oct-15 4:42 
AnswerRe: why they name that "interpolation"? Pin
jrobb22924-Dec-15 13:06
jrobb22924-Dec-15 13:06 
SuggestionOut of date syntax Pin
Dennis_E30-Apr-15 22:15
professionalDennis_E30-Apr-15 22:15 
GeneralI've always liked this form of "formatting" Pin
Bill Gord27-Apr-15 10:28
professionalBill Gord27-Apr-15 10:28 
Questioninjection Pin
SuperToha27-Apr-15 4:21
SuperToha27-Apr-15 4:21 
AnswerRe: injection Pin
Luiz Monad27-Apr-15 9:48
professionalLuiz Monad27-Apr-15 9:48 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.