WriteLine( ) and Output
The .NET Framework provides a useful method for displaying output on the screen in console applications: System.Console.WriteLine( ). How you use this method will become clearer as you progress through the book, but the fundamentals are straightforward. You call the method, and in the parentheses you pass in a string that you want printed to the console (the screen), as in the Hello World application in Chapter 1.
That’s useful; a string is fixed text, and you might want to output a value that can change, depending on the content of your program. For that, you can also pass in substitution parameters. A substitution parameter is just a placeholder for a value you want to display. For example, you might pass in the substitution parameter {0} as part of the string, and then when you run the program, you’ll substitute the value held in the variable myInt so that its value is displayed where the parameter {0} appears in the WriteLine( ) statement.
Here’s how it works. Each substitution parameter is a number between braces, starting with 0 for the first parameter, 1 for the next, and so on. So, if you’re using just one substitution parameter, it might look like this:
System.Console.WriteLine("Age of student: {0}", myInt);Notice that you follow the quoted string with a comma and then a variable name. The value of the variable will be substituted into the parameter. If myInt has the value 15, the statement shown previously causes the following to display:
Age of student: ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access