The value of {} expressions

I am new to C # programming. I am reading a C # book and I am having trouble interpreting the code. In particular, how do the functions {0} and my_double work?

my_double = 3.14;
my_decimal = 3.14;
Console.WriteLine("\nMy Double: {0}", my_double);

I saw this format several times in the book, but it was not explained. I know that he writes this in a console window, but my questions are:

  • What does it mean?
  • Why it has {0} in braces, it can be replaced with any other number, for example {100}
  • How can I use several variables in the last line of code to say print my_decimal as well.
+4
source share
6 answers

1) This means that {0} will be replaced by the first (zero) parameter after the line. It is similar to the syntax used string.Format(...).

2) {100} , 101- . .

3) , () . :

int param1 = 1;
string param2 = "hello";
double param3 = 2.5;
Console.WriteLine("This is parameter 1: {0}. This is parameter 2: {1}. This is parameter 3: {2}", param1, param2, param3);

Docs:

+9

. , , 0- , my_double. , "blah" + variable + "blah" + variable2...

, . IE:

Console.WriteLine("{0}{1}{2}", var0, var1, var2);
+2

Console.WriteLine, . , , {x}. 0, , , WriteLine("{0},{1}", value1, value2). WriteLine ; http://msdn.microsoft.com/en-us/library/586y06yf(v=vs.110).aspx

0

string.Format. , :

 my_double = 3.14;
 my_decimal = 3.14;

Console.WriteLine("\nMy Double: {0}\nMy Decimal: {1}", my_double, my_decimal);
0

String.Format: {sequentialInteger} ( ) .

:

my_double = 3.14;
my_decimal = 3.14;

Console.WriteLine("\nMy Double: {0} here your decimal: {1}", my_double, my_decimal );
//output: My Double: 3.14 here your decimal: 3.14


Console.WriteLine("\nMy Double: {2} here your decimal: {0}", "foo", my_decimal, DateTime.Now.ToShortDate() );
//output: My Double: 12/10/2013 here your decimal: foo
0

See the documentation for Concole.WriteLine (or String.Format). {0} indicates the token that will be replaced by the next parameter in the function .... so ...

Console.WriteLine("One {0}, Two {1}, Three {2}, One {0}", 1, 2, 3);

Will produce:

One 1, Two 2, Three 3, One 1

You can use {0: n} or other formatting options to render the value in a specific string format.

http://msdn.microsoft.com/en-us/library/a0bfz20d(v=vs.110).aspx

0
source

All Articles