DownForNow
DownForNow

Reputation: 45

How do I add a reference from a for loop to the string format in the WriteLine function?

I have looked about everywhere (exaggeration) before I started asking the question and have come up with nothing, I think the question may be confusing but I am trying to pass the variable i to the parameters in the WriteLine(..) method string, here is an example;

Expression<Func<int, int, int>> expression = (a, b) => a + b;
        for(int i = 0; i < expression.Parameters.Count; i++)
        {
            Console.WriteLine("Expression param[{i+1}]: {i}", expression.Parameters[i]);
        }

Is this valid in c#? to add the int i into the Console.WriteLine(..) method.

I have also tried:

Console.WriteLine("Expression param[{" + i+1 +"}]: {"+ i +"}", expression.Parameters[i]);

Upvotes: 2

Views: 324

Answers (2)

Joel R Michaliszen
Joel R Michaliszen

Reputation: 4222

It work's

Console.WriteLine("Expression param[{0}]: {1}", i+1, expression.Parameters[i]);

But if you are using C# 6, string interpolation is better:

Console.WriteLine($"Expression param[{i+1}]: {expression.Parameters[i]}");

String interpolation lets you more easily format strings. String.Format and its cousins are very versatile, but their use is somewhat clunky and error prone. Particularly unfortunate is the use of numbered placeholders like {0} in the format string, which must line up with separately supplied arguments.

ref: https://blogs.msdn.microsoft.com/csharpfaq/2014/11/20/new-features-in-c-6/

Upvotes: 4

Arturo Menchaca
Arturo Menchaca

Reputation: 15982

Use it in this way:

Console.WriteLine("Expression param[{0}]: {1}", i, expression.Parameters[i]);

{0} refers to the first argument after the format (i).

{1} refers to the second argument after the format (expression.Parameters[i]).

And so on.

Upvotes: 0

Related Questions