In ra console: Console.WriteLine (có newline), Console.Write (không newline), Console.WriteLine(format, args) (composite formatting).
Ví dụ minh họa
using System;
class Program
{
static void Main()
{
string str = "Tom Hanks is an actor";
// WriteLine - tự động xuống dòng
Console.WriteLine("Displaying a line below");
Console.WriteLine(str);
// Write - không xuống dòng
Console.Write("Part 1: ");
Console.Write("Part 2: ");
Console.WriteLine("Part 3 (with newline)");
// Composite formatting
Console.WriteLine("Name: {0}, Age: {1}", "An", 25);
// Interpolation (C# 6+)
Console.WriteLine($"Name: {"An"}, Age: {25}");
// Format số
Console.WriteLine("Pi = {0:F4}", Math.PI); // 3.1416
// Màu sắc (Windows)
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Green text!");
Console.ResetColor();
}
}
Kết quả đầu ra
Displaying a line below Tom Hanks is an actor Part 1: Part 2: Part 3 (with newline) Name: An, Age: 25 Name: An, Age: 25 Pi = 3.1416 Green text!
Phương thức hữu ích khác:
Console.ReadLine()- đọc dòng inputConsole.ReadKey()- đọc 1 phímConsole.Clear()- xóa màn hìnhConsole.SetCursorPosition(left, top)- di chuyển con trỏConsole.Beep()- phát beep