DEV Community

Cover image for Console.WriteLine in C#: How To Use It
ByteHide
ByteHide

Posted on • Originally published at bytehide.com

Console.WriteLine in C#: How To Use It

Understanding the Basics: What is Console.WriteLine in C#?

So, let’s get started with the fundamental question. What is Console.WriteLine in C#? Don’t worry, it’s easier than it sounds.

A Brief Introduction to Console.WriteLine

Console.WriteLine is a method in C# used to display output on the console. It’s like the messenger in the old times who’d shout out messages to the public. In the world of C#, Console.WriteLine does the same. It shouts out your output to the console!

// Let's see how you can print "Hello, World!" using Console.WriteLine
Console.WriteLine("Hello, World!");
Enter fullscreen mode Exit fullscreen mode

This simple line of code will display Hello, World! on the console. Now, I know what you’re thinking: “That was easy!” Well, you’re absolutely right. It’s a piece of cake! But remember, the important part here is understanding how Console.WriteLine works.

The Importance of Console.WriteLine in C#

Console.WriteLine in C# works as the communicator between the application and its user. It prints the program output, debugging information, or any necessary details you want to show. It’s like a tour guide making things simpler for you when you’re wandering in the vast aspiration of a C# application.

The Core of C#: How to Use Console.WriteLine in C#

Ready for some action with Console.WriteLine? Let’s dive a little deeper.

Syntax and Structure of Console.WriteLine

Being the basis of C# output, the usage of Console.WriteLine involves a specific syntax. You could think of it as a superhero with a secret handshake. This secret handshake is mainly the syntax of how you use it.

Let’s look at the typical Console.WriteLine syntax:

Console.WriteLine(object);
Enter fullscreen mode Exit fullscreen mode

Here, ‘object’ can be string, int, boolean, etc. So if you’re looking to print “Hello, Universe!”, the code line would go:

Console.WriteLine("Hello, Universe!");
Enter fullscreen mode Exit fullscreen mode

And voilà, Hello, Universe! displays on your console.

Case Study: Real-Life Example of Using Console.WriteLine

Remember when I said you can also print integers, booleans, and other data types using Console.WriteLine? Well, let’s not just stop at simple strings or integers. Let’s take it up a notch and see how we can print more complex data, such as arrays, lists, and custom objects using Console.WriteLine.

Variable Printing

Let’s quickly recap printing a variable. Say, you have an integer:

int score = 100;
Console.WriteLine(score);
Enter fullscreen mode Exit fullscreen mode

This will print 100 on your console. Here, score is an integer variable stored in memory, and we’re just calling our trusty Console.WriteLine to display it.

Array Printing

Now, let’s say you have an array of integers:

int[] scores = {100, 95, 88, 70, 85};
Enter fullscreen mode Exit fullscreen mode

One approach is to iterate over this array and print each score individually:

foreach(int score in scores) 
{
    Console.WriteLine(score);
}
Enter fullscreen mode Exit fullscreen mode

As a result, each score will be printed on its own line in the console.

List Printing

Printing a list is quite similar to printing an array. For instance, you might have a list of student names:

List<string> students = new List<string>() {"Adam", "Beth", "Charlie", "Diane"};
Enter fullscreen mode Exit fullscreen mode

You can print this list of students as follows:

foreach (string student in students)
{
    Console.WriteLine(student);
}
Enter fullscreen mode Exit fullscreen mode

Once again, each student’s name will appear on its own line in the console. So far, so good!

Custom Object Printing

To print a custom object, you simply call Console.WriteLine with the object as its parameter. However, the output might not meet your expectations.

For example, let’s say you have a simple Student class:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }
}
Enter fullscreen mode Exit fullscreen mode

And you create a Student object and try to print it:

Student student = new Student { Name = "John Doe", Age = 20 };
Console.WriteLine(student);
Enter fullscreen mode Exit fullscreen mode

You might expect it to print something like “John Doe, 20”, but instead, you’ll get something along the lines of “Namespace.Student”.

What’s happening? Well, when you call Console.WriteLine with an object, it calls the ToString method on that object. The default implementation of ToString simply returns the name of the type of the object, which isn’t particularly helpful.

Here’s a simple fix: Override the ToString method in the Student class:

public class Student
{
    public string Name { get; set; }
    public int Age { get; set; }

    public override string ToString()
    {
        return $"{Name}, {Age}";
    }
}
Enter fullscreen mode Exit fullscreen mode

Now if you run the same code:

Student student = new Student { Name = "John Doe", Age = 20 };
Console.WriteLine(student);
Enter fullscreen mode Exit fullscreen mode

You get the expected result: “John Doe, 20”.

In this extended example, we’ve navigated through printing variables, arrays, lists, and custom objects using Console.WriteLine. These real-life examples should help you understand the versatility of Console.WriteLine and how you can use it to present different types of data in your C# programs.

Where Does Console.WriteLine Go in C#?

Alright, we learned how to use Console.WriteLine in C#, but where exactly it goes? Ever thought about it?

Understanding Console Output

The output of Console.WriteLine goes directly to a console application window, aka terminal. It’s like sending postcards. You write it (Console.WriteLine), it gets sent and goes straight to the recipient (the console application window).

Using Console.WriteLine to Direct Outputs

Think of Console.WriteLine as the director of a play, controlling where each character (in our case, output) goes on the stage (console window).

Here’s how you get text to appear exactly where it’s supposed to go:

Console.WriteLine("This is output line 1");
Console.WriteLine("This is output line 2");
Enter fullscreen mode Exit fullscreen mode

After running this, you’d see:

This is output line 1
This is output line 2
Enter fullscreen mode Exit fullscreen mode

See how Console.WriteLine arranged our outputs?

Comparing Techniques: C# Console.WriteLine vs Print to Console

Outputting to the console is a fundamental part of C#. Regardless of whether you’re practicing code or debugging a complex program, displaying data in the console is crucial. But how to do this effectively?

Understanding C# Print to Console

In C#, we do not have a particular ‘print’ keyword, unlike some other languages. Instead, we have methods like Console.Write and Console.WriteLine. You might be wondering what’s the difference between them. Let’s quickly understand.

Console.Write("Hello");
Console.Write("World");
Enter fullscreen mode Exit fullscreen mode

This will print HelloWorld on a single line. Got it? Console.Write does not append newline at the end.

Now the same code with Console.WriteLine,

Console.WriteLine("Hello">);
Console.WriteLine("World");
Enter fullscreen mode Exit fullscreen mode

This will print:

Hello
World
Enter fullscreen mode Exit fullscreen mode

See the difference? Console.WriteLine appends a newline at the end. So, your next print will be on a new line.

Comparing Efficiency: When to Use Console.WriteLine or Print to Console

The debate about Console.WriteLine vs. Console.Write or how to print to console in C# always ignites a spark. The answer, however, depends on the specific requirement.

Here’s a table comparing Console.WriteLine and Console.Write:

Method Newline Usage
Console.WriteLine() Yes When you want output on separate lines.
Console.Write() No When continuous output on the same line is required.

Now, let’s see how C# offers fantastic control over what and how you print.

Consider this:

int age = 30;
string name = "John";
Console.WriteLine("Hello, my name is {0} and I am {1} years old.", name, age);
Enter fullscreen mode Exit fullscreen mode

This will output: Hello, my name is John and I am 30 years old.

Impressive, isn’t it?

C# also supports different forms of string interpolation, allowing us to have even more control over our console outputs. Let’s see how:

int age = 30;
string name = "John";
Console.WriteLine($"Hello, my name is {name} and I am {age} years old.");
Enter fullscreen mode Exit fullscreen mode

See, the $ character indicates that the string should parse any variables in it, making it cleaner and easier to understand!

Advantages and Caveats of Using Console.WriteLine in C#

By now, we have got a fair idea about Console.WriteLine. But like everything, it also has its pros and cons. Let’s have a look at them:

Pros of Using Console.WriteLine in C#

  • Ease of Use: Console.WriteLine is straightforward and easy to use; it’s one of the first things one learns in C# programming.
  • Versatility: The method can display nearly all types of data—string, numbers, booleans, etc.

Cons and Common Pitfalls of Using Console.WriteLine in C#

  • Almost invisible output: If you use Console.WriteLine in a console application without a pause at the end (like Console.ReadLine()), the output might fleet away before you can even see it.
  • Cluttered Output: Without proper formatting, the output can become confusing and hard to read, especially when dealing with complex and long messages.

Console.WriteLine is a humble start to explore the vast realm of C#. It’s as fundamental to C# as superheroes to comic books. Always remember, every super-coder started from the basics. What are you waiting for? Start your C# coding journey now with Console.WriteLine and, before you know it, you’ll be the super-coder!

Top comments (1)

Collapse
 
jangelodev profile image
João Angelo

Hi ByteHide,Thanks for sharing