Question

I'm learning C# and came across this small piece of code:

{

  class Program

   {

     static void Main(string[] args)

      {

         int age = 20;// declaring variable and assign 20 to it.

         Console.WriteLine("You are {0} years old.",age);

         Console.ReadLine();

       }

   }

}

I dont understand how {0} will output 20. I mean it's not like an array index or anything so how does it know it's referring to the variable age ? I see the variable after the comma but would that mean that if I put {1} then it would retrieve the variable after age?

Also what is this feature called in C# I can't seem to locate it.

Was it helpful?

Solution

Also what is this feature called in C# I can't seem to locate it.

At the C# level: it isn't - because it isn't a C# feature at all; it is simply a library feature - see also string.Format. This handy utility method locates {0}, {1}, {2} etc and replaces them with the 0th, 1st, 2nd etc arguments. There is more to it that than, obviously (there are more complex formats available - patterns; negative vs positive, etc).

The documentation for Console.WriteLine is here: http://msdn.microsoft.com/en-us/library/828t9b9h.aspx

which links to "Composite Formatting": http://msdn.microsoft.com/en-us/library/txafckwd.aspx - which is what the BCL team call this, with intro:

The .NET Framework composite formatting feature takes a list of objects and a composite format string as input. A composite format string consists of fixed text intermixed with indexed placeholders, called format items, that correspond to the objects in the list. The formatting operation yields a result string that consists of the original fixed text intermixed with the string representation of the objects in the list.

OTHER TIPS

It's like in standard C printf() function. The values are passed after the string and are formated in order the variables are passed.

string.Format("Var1: {0}, var2:{1}, TheVery{3}InHere", "val1", "val2", "LongText");

It is a string formatter and it will be replaced by the value.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top