Using variables inside strings

C#StringString Formatting

C# Problem Overview


In PHP I can do the following:

$name = 'John';
$var = "Hello {$name}";    // => Hello John

Is there a similar language construct in C#?

I know there is String.Format(); but I want to know if it can be done without calling a function/method on the string.

C# Solutions


Solution 1 - C#

In C# 6 you can use string interpolation:

string name = "John";
string result = $"Hello {name}";

The syntax highlighting for this in Visual Studio makes it highly readable and all of the tokens are checked.

Solution 2 - C#

This functionality is not built-in to C# 5 or below.
Update: C# 6 now supports string interpolation, see newer answers.

The recommended way to do this would be with String.Format:

string name = "Scott";
string output = String.Format("Hello {0}", name);

However, I wrote a small open-source library called SmartFormat that extends String.Format so that it can use named placeholders (via reflection). So, you could do:

string name = "Scott";
string output = Smart.Format("Hello {name}", new{name}); // Results in "Hello Scott".

Hope you like it!

Solution 3 - C#

Use the following methods

1: Method one

var count = 123;
var message = $"Rows count is: {count}";

2: Method two

var count = 123;
var message = "Rows count is:" + count;

3: Method three

var count = 123;
var message = string.Format("Rows count is:{0}", count);

4: Method four

var count = 123;
var message = @"Rows
                count
                is:{0}" + count;

5: Method five

var count = 123;
var message = $@"Rows 
                 count 
                 is: {count}";

Solution 4 - C#

Up to C#5 (-VS2013) you have to call a function/method for it. Either a "normal" function such as String.Format or an overload of the + operator.

string str = "Hello " + name; // This calls an overload of operator +.

In C#6 (VS2015) string interpolation has been introduced (as described by other answers).

Solution 5 - C#

I saw this question and similar questions and I preferred to use a built-in method for the problem of using a dictionary of values to fill-in placeholders in a template string. Here's my solution:

    public static void ThrowErrorCodeWithPredefinedMessage(Enums.ErrorCode errorCode, Dictionary<string, object> values)
    {
        var str = new StringFormatter(MSG.UserErrorMessages[errorCode]) { Parameters = values};
        var applicationException = new ApplicationException($"{errorCode}", new ApplicationException($"{str.ToString().Replace("@","")}"));
        throw applicationException;
    }

where the message exists in a Dictionary that is not in the caller, but the caller only has access to Enums.ErrorCode, and can build an argument array and send it to the above method as argument.

assuming we have the value of MSG.UserErrorMessages[errorCode] is originally

"The following entry exists in the dump but is not found in @FileName: @entryDumpValue"

The result of this call

 var messageDictionary = new Dictionary<string, object> {
                    { "FileName", sampleEntity.sourceFile.FileName}, {"entryDumpValue", entryDumpValue }
                };
                ThrowErrorCodeWithPredefinedMessage(Enums.ErrorCode.MissingRefFileEntry, messageDictionary);

is

The following entry exists in the dump but is not found in cellIdRules.ref: CellBand = L09

The only restriction to this approach is to avoid using '@' in the contents of any of the passed values.

Solution 6 - C#

you can define a variable as string like this in C#

var varName= data.Values["some var"] as string;

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionthwdView Question on Stackoverflow
Solution 1 - C#FentonView Answer on Stackoverflow
Solution 2 - C#Scott RippeyView Answer on Stackoverflow
Solution 3 - C#Abn NajafView Answer on Stackoverflow
Solution 4 - C#Anders AbelView Answer on Stackoverflow
Solution 5 - C#Michael BahigView Answer on Stackoverflow
Solution 6 - C#farhad kazemipourView Answer on Stackoverflow