String Interpolation with format variable
No, you can't use string interpolation with something other than a string literal as the compiler creates a "regular" format string even when you use string interpolation.
Because this:
string name = "bar";
string result = $"{name}";
is compiled into this:
string name = "bar";
string result = string.Format("{0}", name);
the string in runtime must be a "regular" format string and not the string interpolation equivalent.
You can use the plain old String.Format
instead.
C# How to treat a string variable as interpolated string?
String interpolation is a compiler feature, so it cannot be used at runtime. This should be clear from the fact that the names of the variables in the scope will in general not be availabe at runtime.
So you will have to roll your own replacement mechanism. It depends on your exact requirements what is best here.
If you only have one (or very few replacements), just do
output = input.Replace("{date}", date);
If the possible replacements are a long list, it might be better to use
output = Regex.Replace(input, @"\{\w+?\}",
match => GetValue(match.Value));
with
string GetValue(string variable)
{
switch (variable)
{
case "{date}":
return DateTime.Today.ToString("MMddyyyy");
default:
return "";
}
}
If you can get an IDictionary<string, string> mapping variable names to values you may simplify this to
output = Regex.Replace(input, @"\{\w+?\}",
match => replacements[match.Value.Substring(1, match.Value.Length-2)]);
String interpolation with variable from resource
We have the FormattableString class and the FormattableStringFactory.
This is how to use them
string error = "Apple";
// This comes from your resourse.
string myErrorMessage = "Fruit with name '{0}' does not exist.";
FormattableString s = FormattableStringFactory.Create(myErrorMessage, error);
string message = s.ToString();
However you still need to change your resources files to be as expected by the FormattableStringFactory. You need also to add the System.Runtime.CompilerServices namespace to your project
String interpolation into a variable
${Body}
doesn't compile.
You can't generate the interpolation at run-time, it is a syntactic sugar that gets transformed by the compiler into String.Format
.
You can solve your problem by using Replace
from StringBuilder
or String
:
sb.Replace("{p.FirstName}", p.FirstName);
How to use variable inside interpolated string?
You are missing a $
var name = "mike";
var desc = $"hello world {name}"; // this needs be interpolated as well
var t = $"{desc}";
Console.WriteLine(t); // PRINTS: hello world mike
Additional Resources
$ - string interpolation (C# Reference)
The $ special character identifies a string literal as an interpolated
string. An interpolated string is a string literal that might contain
interpolated expressions. When an interpolated string is resolved to a
result string, items with interpolated expressions are replaced by the
string representations of the expression results. This feature is
available in C# 6 and later versions of the language.
Update
but suppose I want to have a variable storing the string with {name}
in it. Is there no way to achieve interpolation if its in a variable?
No you would have to use standard String.Format
Tokens
var tokenString = "Something {0}";
String.Format(tokenString,someVariable);
String.Format Method
Converts the value of objects to strings based on the formats
specified and inserts them into another string.Use String.Format if you need to insert the value of an object,
variable, or expression into another string. For example, you can
insert the value of a Decimal value into a string to display it to the
user as a single string:
Composite Formatting
The .NET composite formatting feature takes a list of objects and a
composite format string as input. A composite format string consists
of fixed text intermixed with indexed placeholders, called format
items, that correspond to the objects in the list. The formatting
operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.
String Interpolation in variable
You can't interpolate like that. The Jiter just wont have any clue of the context or as to when to use that variable.
If you think it through, when should it replace it. On first use? What if you wanted to replace multiple Representations in different contexts, which scope should it consider. Sounds very unpredictable
However, if its an consolation. You could do this
public static string SetScore = "Score[@Set='{0}']";
...
result = string.Format(SetScore,currentSet)
Interpolated Strings (C# Reference)
Used to construct strings. An interpolated string looks like a
template string that contains interpolated expressions. An
interpolated string returns a string that replaces the interpolated
expressions that it contains with their string representations.
Moreso
You can use an interpolated string anywhere you can use a string
literal. The interpolated string is evaluated each time the code with
the interpolated string executes. This allows you to separate the
definition and evaluation of an interpolated string.
Why don't C# interpolated strings accept variable padding?
You need to make pad a constant:
foreach (var item in new string[] { "cat", "dog", "mouse" })
{
const int pad = -12;
Console.WriteLine($"{item, pad}");
}
If a constant cannot be used, then you must use a string padding function, such as PadLeft, or PadRight.
A constant value is expected in string interpolation
In this case you might be better off to use string.Format than interpolation.
var str = "test";
var width = 10;
var fmt = $"{{0,{width}}}";
var result = string.Format(fmt, str);
But if you're simply padding with spaces PadLeft
or PadRight
would be cleaner...
return str.PadLeft(width, ' ');
How to use string interpolation in a resource file?
You can't make use of string interpolation in the context of resources. However you could achieve that you want by making use of string.Format
. Write to your resource file something like this:
Hello {0}
and then use it like below:
public static string message (string userName)
{
return string.Format(Resource.WebResource.EmailConfirmation, userName);
}
Update
You can add as many parameters as you want. For instance:
Hello {0}, Confirm your email: {1}
And then you can use it as:
string.Format(Resource.WebResource.EmailConfirmation
, userName
, HtmlEncoder.Default.Encode(link))
Related Topics
How to Find Duplicates in an Array and Display How Many Times They Occurred
Topmost Form, Clicking "Through" Possible
Perform Screen-Scape of Webbrowser Control in Thread
Concurrentdictionary Getoradd Async
Is an Int a 64-Bit Integer in 64-Bit C#
Google Maps V3 Geocoding Server-Side
Synchronizationlockexception on Monitor.Exit When Using Await
Any Trick to Use Opacity on a Panel in Visual Studio Window Form
How to Set a Proxy for Webbrowser Control Without Effecting the System/Ie Proxy
Unity 5.5 Obsolete Particle System Code
Error "This Stream Does Not Support Seek Operations" in C#
Visualizing an Ast Created with Antlr (In a .Net Environment)
How to Get a Unique Identifier for a Device Within Windows 10 Universal
Why Would Try/Finally Rather Than a "Using" Statement Help Avoid a Race Condition