In this article, you will learn:
- String concatenation in C# (Old mechanism vs New mechanism)
- What is String Interpolation in C#?
- How does it work?
What is String Interpolation in C#
String Interpolation is a mechanism to concatenate two or more strings together.
In older versions of C#, we were using “+” operator or string. Format method was used to concatenate strings, but in C# 6.0, Microsoft has provided a feature named String Interpolation to concatenate strings.
Let’s see an example of Customer class where we will concatenate the first name and last name using traditional ways of concatenation.
Traditional ways of String Concatenation:
Using “+” Operator
- class Customer
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public string Email
- {
- get;
- set;
- }
- public int age
- {
- get;
- set;
- }
- static void Main(string[] args)
- {
-
- Customer cus = new Customer();
- cus.FirstName = "Lana";
- cus.LastName = "Leonard";
- cus.Email = "[email protected]";
- cus.age = 31;
- Console.WriteLine("Name : " + cus.FirstName + " " + cus.LastName + "\nEmail : " + cus.Email);
- Console.ReadLine();
- }
- }
Using String.Format method - class Customer
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public string Email
- {
- get;
- set;
- }
- public int age
- {
- get;
- set;
- }
- static void Main(string[] args)
- {
-
- Customer cus = new Customer();
- cus.FirstName = "Lana";
- cus.LastName = "Leonard";
- cus.Email = "[email protected]";
- cus.age = 31;
- Console.WriteLine(string.Format("Name : {0} {1}\nEmail : {2}", cus.FirstName, cus.LastName, cus.Email));
- Console.ReadLine();
- }
- }
New ways of String Concatenation Using String Interpolation:
By using the new String Interpolation feature in C# 6.0, you can:
- Place the String whereever you want it.
- Use conditions.
- Specify space before / after the string.
So, let’s see an example to implement the above 3 scenarios using String Interpolation.
- class Customer
- {
- public string FirstName
- {
- get;
- set;
- }
- public string LastName
- {
- get;
- set;
- }
- public string Email
- {
- get;
- set;
- }
- public int age
- {
- get;
- set;
- }
- static void Main(string[] args)
- {
-
- Customer cus = new Customer();
- cus.FirstName = "Lana";
- cus.LastName = "Leonard";
- cus.Email = "[email protected]";
- cus.age = 31;
-
- Console.WriteLine("Name : \{cus.FirstName} \{cus.LastName}\nEmail : \{cus.Email}\nAge :\{cus.Age}");
-
- Console.WriteLine("Name : \{cus.FirstName,5} \{cus.LastName}\nAge :\{cus.Age:A2}");
-
- Console.WriteLine("Name : \{cus.FirstName, 5} \{cus.LastName}\nMessage :\{cus.Age>=30?"
- " :"
- Senior Developer "}");
- Console.ReadLine();
- }
- }