I'm new to C#. I was solving some basic problems or challenges you might say just for practicing. I try to solve it by myself first and then check the output from the source. I check tutorials from YouTube to learn. It's not much of an issue but I fail to come up with a name to search about this representation format used in Console.WriteLine
method.
Main Source Link: https://www.w3resource.com/csharp-exercises/basic/index.php
Image of the question: 7.no Exercise
My own code as solve:
int a; int b; float d; float e; //variables
int plus; int minus; int mult; float div; float mod; //operators
Console.WriteLine("Input the first number:");
a = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Input the second number:");
b = Convert.ToInt32(Console.ReadLine());
plus = a b ;
minus = a - b ;
mult = a * b ;
div = a / b ;
mod = a % b ;
Console.WriteLine("\n\n\n");
Console.WriteLine($"{a} {b} = {plus}");
Console.WriteLine($"{a} - {b} = {minus}");
Console.WriteLine($"{a} x {b} = {mult}");
Console.WriteLine($"{a} / {b} = {div}");
Console.WriteLine($"{a} mod {b} = {mod}");
Console.WriteLine("\n\nPress any Key to Exit.");
Console.ReadKey();
Solved sample Code from source:
Console.Write("Enter a number: ");
int num1= Convert.ToInt32(Console.ReadLine());
Console.Write("Enter another number: ");
int num2= Convert.ToInt32(Console.ReadLine());
Console.WriteLine("{0} {1} = {2}", num1, num2, num1 num2);
Console.WriteLine("{0} - {1} = {2}", num1, num2, num1-num2);
Console.WriteLine("{0} x {1} = {2}", num1, num2, num1*num2);
Console.WriteLine("{0} / {1} = {2}", num1, num2, num1/num2);
Console.WriteLine("{0} mod {1} = {2}", num1, num2, num1%num2);
I understand mine but the one from the source is a bit unknown for me, the use of 0,1,2 in second brackets entangled with those variables. Could someone tell me about both output formats with bit of a details?
CodePudding user response:
What you do is called string interpolation. What is showed in the example is composite formatting. You can find out more about these topics at ms-docs.
With string interpolation you put a $ sign before the "" of your string, so the compiler knows how to treat that string. Then you just use {} inside your string and anything inside those {} is then ran just like any other piece of code. An example would be:
string myName = "Captain Coder"
int myAge = 21;
Console.WriteLine($"They know me as {myName} for {myAge} years now.");
output: They know me as Captain Coder for 21 years now.
With composite formatting you just put the index of the parameter between {} to use at the given place. Example:
string myName = "Captain Coder"
int myAge = 21;
Console.WriteLine("They know me as {0} for {1} years now.", myName, myAge);