PKonstant
PKonstant

Reputation: 988

Easy C# question about the Debug.Writeline() with parameters

While debugging my application, I came across a behavior I'm puzzled by. I have the following

foreach (var customer in _dbContext.Customer)
{
  Debug.WriteLine("Customer Name: {0}", customer.Name);  // The output was not what I expected.
...
}

Actual Output

Peter:Customer Name: {0}

However, if I rewrite the statement to this.

foreach (var customer in _dbContext.Customer)
{
  Debug.WriteLine("Customer Name: " + customer.Name);  
...
}

Actual Output

Customer Name: Peter

I added the following the code to the same file to see why my original code wasn't working.

string first = "Peter";
string last = "Piper";
string what = "pick";
Debug.WriteLine("1 {0} 2 {1}, 3 {0} 4 {1}, 5 {2}.", first, last, what);

Actual Output

1 Peter 2 Piper, 3 Peter 4 Piper, 5 pick.

I am not sure why Debug.WriteLine("Customer Name: {0}", customer.Name); would output this CusPeter:Customer Name: {0}

Many Thanks

Upvotes: 1

Views: 956

Answers (2)

Jlalonde
Jlalonde

Reputation: 483

A working alternative is using $ string interpolation

Yielding this

Debug.Writline($"CustomerName {customer.Name});

I accidently answered this in comments but found out the the actual reason is answered here and that we're hitting the wrong overload, and not the one for interpolation.

Upvotes: 1

Stormhashe
Stormhashe

Reputation: 704

The problem happens because of the overload of the method. When you pass a string as a second parameter, it maps to the following method:

enter image description here

As you can see, this overload is not expecting "arguments", as you would when you want to replace them in a string, but rather is waiting for a "category" of the de Debug information.

The code casting your string to object works because of the following overload:

enter image description here

As you can see, when you cast your string to "object", it maps to another overload of the WriteLine method, which is actually expecting values to be formatted into a string. I believe this answers your doubt about why it works when casting to object.

Upvotes: 3

Related Questions