Getting Started With C#
Literals
Operators
Conditional Statements
Equality Operator
Equals and GetHashCode
Null-Coalescing Operator
Null-Conditional Operators
nameof Operator
Verbatim String
Common String Operations
String Format
String Concatenate
String Manipulation
String Interpolation
Basics of string interpolation
Behind the scenes
Format numbers in strings
Format dates in strings
Padding the output
Left Padding
Right Padding
Padding with Format Specifiers
Expressions
String Escape Sequences
StringBuilder
Regex
DateTime
Arrays
On Algorithm for circular rotation of an array
Enum
Tuples
Overview of C# collections
GUID
BigInteger
Collection Initializers
Looping
Iterators
IEnumerable
Value type vs Reference type
Built-in Types
Aliases of built-in types
Anonymous types
Dynamic type
Type Conversion
Casting
Nullable types
Constructors and Finalizers
Access Modifiers
Interfaces
Static Classes
Singleton Implementation
Dependency Injection
Partial class and methods
Object Initializers
Methods
Extension Methods
Named Arguments
Named And Optional Arguments
Data Annotation
Keywords
Recursion
Naming Conventions
XML Documentation Comments
Comments and regions
Inheritance
Generics
Using Statement
Using Directive
IDisposable interface
Reflection
IQueryable interface
LINQ to Objects
LINQ Queries
LINQ to XML
Parallel LINQ PLINQ
XmlDocument
XDocument
C# 7.0 Features
C# 6.0 Features
C# 5.0 Features
C# 4.0 Features
C# 3.0 Features
Exception Handling
NullReferenceException
Handling FormatException
Read and Understand Stack trackes
Diagnostics
Overflow
JSON handling
Using json.net
Lambda Expressions
Lambda expressions
Generic Lambda Query Builder
Properties
Initializing Properties
INotifyPropertyChanged interface
Events
Expression Trees
Overload Resolution
Preprocessor directives
Structs
Attributes
Delegates
File and Stream IO
Networking
Performing HTTP requests
Reading and writing .zip files
FileSystemWatcher
Asynchronous Socket
Action Filters
Polymorphism
Immutability
Indexer
Checked and Unchecked
Stream
Timers
Stopwatches
Threading
Async/Await, BackgroundWorker, Task and Thread examples
Async Await
Synchronization Context in Async/Await
BackgroundWorker
Task Parallel Library
Making a variable thread safe
Lock Statement
Yield Keyword
Task Parallel Library TPL Dataflow Constructs
Functional Programming
Func delegates
Function with multiple return values
Binary Serialization
ICloneable
IComparable
Accessing Databases
Using SQLite
Caching
Code Contracts
Code Contracts and Assertions
Structural Design Patterns
Creational Design Patterns
Implementing Decorating Design Pattern
Implementing Flyweight Design Pattern
System.Management.Automation
Pointers
Pointers and Unsafe Code
Simulating C Unions with C# Structs
Reactive Extensions Rx
AsseblyInfo.cs examples
Creating Console Application
CLSCompliantAttribute
ObservableCollection<T>
Hash Functions
Generating Random Numbers
Cryptography
Unsafe Code in .NET
C# Script
Runtime Compile
Interoperability
.NET Compiler Platform Roslyn
Creating Own MessageBox in Windows Form Application
Including Font Resources
Garbage Collector
Windows Communication Foundation
Contributors

String Interpolation

suggest change

String interpolation is a syntactic shorthand for the string.Format() introduced in C# 6.

var name = "World";
var oldWay = string.Format("Hello, {0}!", name);  // returns "Hello, World"
var newWay = $"Hello, {name}!";                   // returns "Hello, World"

Basics of string interpolation

var name = "World";
var str = $"Hello, {name}!";
//str now contains: "Hello, World!";

Behind the scenes

Internally this

$"Hello, {name}!"

Will be compiled to something like this:

string.Format("Hello, {0}!", name);

Format numbers in strings

You can use a colon and the standard numeric format syntax to control how numbers are formatted.

var decimalValue = 120.5;

var asCurrency = $"It costs {decimalValue:C}";
// String value is "It costs $120.50" (depending on your local currency settings)

var withThreeDecimalPlaces = $"Exactly {decimalValue:F3}";
// String value is "Exactly 120.500"

var integerValue = 57;

var prefixedIfNecessary = $"{integerValue:D5}";
// String value is "00057"

Live Demo on .NET Fiddle

Format dates in strings

var date = new DateTime(2015, 11, 11);
var str = $"It's {date:MMMM d, yyyy}, make a wish!";
System.Console.WriteLine(str);

You can also use the DateTime.ToString method to format the DateTime object. This will produce the same output as the code above.

var date = new DateTime(2015, 11, 11);
var str = date.ToString("MMMM d, yyyy");
str = "It's " + str + ", make a wish!";
Console.WriteLine(str);

Output:

It’s November 11, 2015, make a wish!

Live Demo on .NET Fiddle

Live Demo using DateTime.ToString

Note: MM stands for months and mm for minutes. Be very careful when using these as mistakes can introduce bugs that may be difficult to discover.

Padding the output

String can be formatted to accept a padding parameter that will specify how many character positions the inserted string will use :

${value, padding}
NOTE: Positive padding values indicate left padding and negative padding values indicate right padding.

Left Padding

A left padding of 5 (adds 3 spaces before the value of number, so it takes up a total of 5 character positions in the resulting string.)

var number = 42;
var str = $"The answer to life, the universe and everything is {number, 5}.";
//str is "The answer to life, the universe and everything is    42.";
//                                                           ^^^^^
System.Console.WriteLine(str);

Output:

The answer to life, the universe and everything is    42.

Live Demo on .NET Fiddle

Right Padding

Right padding, which uses a negative padding value, will add spaces to the end of the current value.

var number = 42;
var str = $"The answer to life, the universe and everything is ${number, -5}.";
//str is "The answer to life, the universe and everything is 42   .";
//                                                           ^^^^^
System.Console.WriteLine(str);

Output:

The answer to life, the universe and everything is 42   .

Live Demo on .NET Fiddle

Padding with Format Specifiers

You can also use existing formatting specifiers in conjunction with padding.

var number = 42;
var str = $"The answer to life, the universe and everything is ${number, 5:f1}";
//str is "The answer to life, the universe and everything is 42.1 ";
//                                                           ^^^^^

Live Demo on .NET Fiddle

Expressions

Full expressions can also be used in interpolated strings.

var StrWithMathExpression = $"1 + 2 = {1 + 2}"; // -> "1 + 2 = 3"

string world = "world";
var StrWithFunctionCall = $"Hello, {world.ToUpper()}!"; // -> "Hello, WORLD!"

Live Demo on .NET Fiddle

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents
15 String Interpolation
18 Regex
20 Arrays
22 Enum
23 Tuples
25 GUID
89 Events
105 Indexer
107 Stream
108 Timers
128 Caching