String Interpolation is nothing but a way to concatenate two or more strings together. As we aware of, in previous version of .NET we did string concatenation using the + (plus) operator. Sometimes for the same work we have also used the String.Format method. Now we are pleased to hear that it became the old way to do string concatenation.
Old ways to concatenate strings :
1) The + operator
Console.WriteLine("Name : "+ si.FirstName+" "+si.LastName+"\nEmail : "+si.Email);
2) With spaces
Console.WriteLine(string.Format("Name : {0} {1}\nEmail : {2}", si.FirstName, si.LastName, si.Email));
C# 6.0 is the newest version of C#, Microsoft added a very nice feature to accelerate our program code. Now we can put expressions directly in the string literal to show the values in an actual manner. In C# 6.0 we can easily specify various formats in our values. We can do the following.
- Place strings where we need them
Console.WriteLine("Name : \{si.FirstName} \{si.LastName}\nEmail : \{si.Email}\nAge :\{si.Age}");
- Specify a space after/before the string
Console.WriteLine("Name : \{si.FirstName,10} \{si.LastName}\nAge :\{si.Age :D2}");
- Use conditions
//Putting Condition in string literal, If Age==25 it will display Age: Age is Over else Age in int value
Console.WriteLine("Name : \{si.FirstName, 10} \{si.LastName}\nAge :\{si.Age==25?"" :"Age is Over"}");
- Using $
Console.WriteLine( $"{nameof(Person)}(FirstName: {si.FirstName}, LastName: {si.LastName}, Age: {si.Age})";
########################################
using System;
public class Program
{
public class Person
{
public string FirstName { get; protected set; }
public string LastName { get; protected set; }
public int Age { get; protected set; }
public Person(string firstName, string lastName, int age) {
FirstName = firstName;
LastName = lastName;
Age = age;
}
public override string ToString()
{
// solution #1
// return string.Format("Person(FirstName: {0}, LastName: {1}, Age: {2}", FirstName, LastName, Age);
// solution #2
// return string.Format("{0}(FirstName: {1}, LastName: {2}, Age: {3})", nameof(Person), FirstName, LastName, Age);
// solution #3
return $"{nameof(Person)}(FirstName: {FirstName}, LastName: {LastName}, Age: {Age})";
}
}
public static void Main()
{
Person p = new Person("John", "Doe", 42);
Console.WriteLine(p);
Console.WriteLine($@"{1+5+7}");
}
}
#################################################
Person(FirstName: John, LastName: Doe, Age: 42)
13
13
#################################################