Is it possible to pass interpolated strings as parameter to a method?

RredCat picture RredCat · Aug 13, 2015 · Viewed 7.3k times · Source

I have started to use Interpolated Strings (new feature of C# 6) and it is really useful and gracefully. But according to my needs I have to pass format of string to a method as a parameter. Something like next:

MyMethod(string format)

In the past, I used it in the next way:

MyMethod("AAA{0:00}")

Now I tried this code:

MyMethod($"AAA{i:00}")

But this doesn't work, because i is created inside of the method and is out of scope in this context.

Is it possible to use any trick for passing interpolated strings as a parameter to a method?

Answer

Kobi picture Kobi · Aug 13, 2015

You cannot do that, and that would not be a very good idea either - it means you are using local variables from another method.
This would defeat the purpose of this feature - to have compiler verifiable string interpolation and binding to local variables.

C# has several good alternatives. For example, using a Func:

public void MyMethod(Func<int,string> formatNumber)
{
    int i = 3;
    var formatted = formatNumber(i);
}

use as:

MyMethod(number => $"AAA{number:00}");

This is better than what you have today - where you have the format string(s?) and its usage in different places.

If you have more than a single variable this approach can scale, but consider grouping them into a class (or a struct) - the func will look much better, and your code will be more readable. This class can also override .ToString(), which might be useful for you.

Another simple option is to pass just the format: MyMethod("00") and i.ToString(format), but that only works in your presumably simplified example.