David
David

Reputation: 15360

String interpolation inside string interpolation

Is it possible to have a variable with a string format that you would like interpolated.

public class Setting
{
    public string Format { get; set; }
}


var setting = new Setting { Format = "The car is {colour}" };
var colour = "black";
var output = $"{setting.Format}";

Expected output

"The car is black".

Upvotes: 3

Views: 3341

Answers (4)

wingerse
wingerse

Reputation: 3796

Why not?
First of all, you can't use a local variable before declaring it in C#. So First declare the colour before using it. Then "interpolate" the string assigned to Format and you are done.

var colour = "black";
var setting = new Setting { Format = $"The car is {colour}" };
var output = $"{setting.Format}";
Console.WriteLine(output);

Output:

The car is black.

Upvotes: 3

Jonesopolis
Jonesopolis

Reputation: 25370

No you can't do that, but you can achieve the same with a slightly different approach, that I've come to like:

public class Setting
{
    public Func<string, string> Format { get; set; }
}

then you can pass your string argument to Format:

var setting = new Setting { Format = s => $"The car is {s}" };
var output = setting.Format("black");

Upvotes: 5

TheLethalCoder
TheLethalCoder

Reputation: 6744

You can do a slight alteration on it, like the following:

public class Setting
{
    public string Format
    { 
        get
        {
            return String.Format(this.Format, this.Colour);
        }
        set
        {
            Format = value;
        }
    }

    public string Colour { get; set; }
}


var setting = new Setting { Format = "The car is {0}", Colour = "black" };

Then the output will be "The car is black".

I haven't tested this code.

Upvotes: 1

SLaks
SLaks

Reputation: 888243

You can't do that. String interpolation is a purely compile-time feature.

Upvotes: 10

Related Questions