3

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".

2
  • Use string.Format. if you have variables and not constants. and you can't have your cake and eat it too. Commented Nov 20, 2015 at 15:14
  • 1
    People have written a bunch of extension methods for this purpose. FormatWith or a similar. Be warned that every one of these custom functions has slightly different behavior. See also Named Formats Redux. Commented Nov 24, 2015 at 14:06

4 Answers 4

10

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

Sign up to request clarification or add additional context in comments.

Comments

5

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");

1 Comment

Which the compiler basically turns into Setting { Format = s => string.Format("The car is {0}", s) };
3

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.

1 Comment

I like this, but can you elaborate for future readers since your change is so subtle?
1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.