# C#: FormattableString

> Today, I just discovered the classroom. FormattableString Two years after it came out. This class has been added with the functionality of string interpolation In…

- Author: Jérôme Giacomini
- Language: en
- Canonical URL: [C#: FormattableString](https://jeromegiacomini.net/articles/2019/03/14/c-formattablestring)
- Published: 2019-03-14
- Last modified: 2026-09-05
- Topics: .NET, C#

Today, I just discovered the classroom. **FormattableString** Two years after it came out.

This class has been added with the functionality of **string interpolation** In C# 6.0.

## String interpolation

String interpolation was a small revolution because it allowed us to make the code much clearer.

For example, to format a string I don't have to write:

```csharp

string firstName = "jérémy";
var title = String.Format("{0} est heureux", firstName);

```


I can write more simply:

```csharp

string firstName = "jérémy";
var title = $"{firstName} est heureux";

```


## But what does this have to do with the FormattableString?

If you want to keep this string and the variables without calculating the **string** because you need to keep the two parts separate .NET provides the class **FormattableString**.

Its use is almost transparent:

```csharp

string firstName = "jérémy";
FormattableString title = $"{firstName} est heureux";

```


**By default any interpolated string can be used as a FormattableString without writing a single line of code.**

![](https://jeromegiacomini.net/Blog/wp-content/uploads/2019/03/jeremy.png)

## Example of use

One of the interesting uses might be to want to transform a **FormattableString** In an encrypted URL string.

```csharp

private string ToUrlFriendly(FormattableString formattableString)
{
   var args = formattableString.GetArguments().Select(arg => WebUtility.UrlEncode(arg.ToString())).ToArray();
   return string.Format(formattableString.Format, args);
}

```


**L’use of the function is very simple:**

```csharp

string search = "jérémie est heureux youtube";

var url = ToUrlFriendly($"https://www.google.com/search?q={search}");

```


Generate:

```csharp

https://www.google.com/search?q=j%C3%A9r%C3%A9mie+est+heureux+youtube

```


## To go further:
  - [The official documentation of FormattableString](https://docs.microsoft.com/fr-fr/dotnet/api/system.formattablestring?view=netframework-4.7.2)
  - [The doc on string interpolation](https://docs.microsoft.com/fr-fr/dotnet/csharp/tutorials/string-interpolation)



Happy coding &##x1f642;

Thanks to Jeremy for reading it carefully.
