-2
using System;

public class Example
{
   public static void Main()
   {
      Console.WriteLine ($"{1:5d}");
   }
}
// The example displays the following output:
// 5d

What does the ":" do in the interpolated string? I know if I write,

$"{1:d5}"

I will get,

00001

but with this I'm not getting an error/warning means it has to mean something that I don't know.

FYI, I'm on C#7.

Hitarth Doctor
  • 126
  • 2
  • 7

2 Answers2

2

It is separator for format string. It allows you to specfy formatting relevant to the type of value on the left. In first case it tries to apply custom format, but since there is no placeholder for actual value - you get only the "value" of the format (try something like Console.WriteLine ($"{1:00000SomeStringAppended}"); for example, "5d" has the same meaning as "SomeStringAppended" in my example). The second one - d5 is a standart decimal format specifier, so you get corresponding output containing formatted value.

Guru Stron
  • 102,774
  • 10
  • 95
  • 132
  • Yeah, I know the format part. What I want to ask is what does $"{1:5d}}" do, so that it returns 5d. it is an in correct format specifier, so why/how does it work? – Hitarth Doctor Jun 07 '21 at 11:29
  • @HitarthDoctor please check the custom format link in the answer. It is a valid custom format (you can put there anything and everything except format specifiers would go in output as is - in your case you have just "5d" string) – Guru Stron Jun 07 '21 at 11:32
  • @HitarthDoctor was glad to help! – Guru Stron Jun 07 '21 at 11:40
1

The following two line would be give the same results - 00001.

var i = $"{1:d5}";
var j = string.Format("{0:d5}", 1);

A colon : in curly brackets is string formatting. You can read more about string formatting here and about string formatting in a string interpolation here

A.Tikadze
  • 86
  • 2