Skip to main content
Published on

WriteLine() Function and Strings in C#

Share:

Introduction

In any programming language, text manipulation and communication with the user are fundamental. In C#, this interaction is frequently carried out through the Console class. In this article, we will focus specifically on the WriteLine() function, the Write() function, and the nature of strings.

Console Functions in Detail

Write() Function

This function allows you to display information in the console. However, it does not move the cursor to the next line after printing. This can be useful for displaying messages on the same line or for waiting for user input immediately afterwards.

Console.Write("Enter your name: ");
string name = Console.ReadLine();
Console.WriteLine($"Hello, {name}!");

WriteLine() Function

WriteLine() is one of the most commonly used functions for displaying data in the console, as it prints the information and automatically moves the cursor to the next line. It is extremely useful for presenting information in an organised way.

ReadKey() Function

In scenarios where you want to pause the program's execution until the user performs some action, the ReadKey() function is perfect. With it, the console waits for a key press, and it is commonly used at the end of programs to prevent the console from closing immediately.

Exploring Strings in Depth

Strings are not just simple sequences of characters. In C#, they come with a variety of methods that make text manipulation and analysis easier.

String Initialisation

A string can be initialised in several ways in C#:

string s1 = "Hello, World!";
string s2 = new string('=', 10); // "=========="

Manipulating Strings

C# offers a range of methods for working with strings:

string s = "Hello, World!";
int size = s.Length; // 13
string uppercase = s.ToUpper(); // "HELLO, WORLD!"
string lowercase = s.ToLower(); // "hello, world!"

Concatenating and Interpolating Strings

We can combine strings using the + operator or string interpolation:

string name = "Mary";
string greeting = "Hello, " + name + "!"; // Hello, Mary!
string interpolatedGreeting = $"Hello, {name}!"; // Hello, Mary!

Conclusion

Mastering the art of string manipulation and console interaction is essential for any C# developer. These are just the basics, and there is much more to explore in the vast universe of C#. We encourage you to delve even deeper to discover all the potential that C# has to offer.

Happy coding!