Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Meaning of {} expressions

Tags:

c#

I am new to C# programming. I am reading a c# book and am having trouble interpreting code. Specifically, how does the {0} and the my_double work below?

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

I have seen this format several times in the book but it hasn't been explained. I know it is writing this to the console window, but my questions are:

  1. What does this mean?
  2. Why does it have {0} in curly brackets could this be replaced by any other number say {100}
  3. How could multiple variables be used in the last line of code to say print out my_decimal also.
like image 712
Villumanati Avatar asked Dec 19 '22 20:12

Villumanati


1 Answers

1) It means the {0} will be replaced with the first (zero-index) parameter after the string. It's similar to the syntax used by string.Format(...).

2) Replacing it with {100} would mean that the 101st parameter would be placed there. That is not a practical use case.

3) You can use multiple variables by adding additional numbers in curly brackets (sequentially) and additional parameters. Like this:

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:

  • Console.WriteLine: http://msdn.microsoft.com/en-us/library/828t9b9h(v=vs.110).aspx
  • String.Format: http://msdn.microsoft.com/en-us/library/b1csw23d(v=vs.110).aspx
like image 200
mayabelle Avatar answered Dec 22 '22 11:12

mayabelle