Hello World - Introductory interactive tutorial
This tutorial teaches you C# interactively, using your browser to write C# and see the results of compiling and running your code. It contains a series of lessons that begin with a "Hello World" program. These lessons teach you the fundamentals of the C# language.
Tip
To paste a code snippet inside the focus mode you should use your keyboard shortcut (Ctrl + v, or cmd + v).
Run your first program
Run the following code in the interactive window. Select the Enter focus mode button. Then, type the following code block in the interactive window and select Run:
Console.WriteLine("Hello World!");
Congratulations! You've run your first C# program. It's a simple program that prints the message "Hello World!". It used the Console.WriteLine method to print that message. Console
is a type that represents the console window. WriteLine
is a method of the Console
type that prints a line of text to that text console.
Let's move on and explore more. The rest of this lesson explores working with the string
type, which represents text in C#. Like the Console
type, the string
type has methods. The string
methods work with text.
Declare and use variables
Your first program printed the string
"Hello World!" on
the screen.
Tip
As you explore C# (or any programming language), you'll make mistakes when you write code. The compiler will find those errors and report them to you. When the output contains error messages, look closely at the example code, and the code in the interactive window to see what to fix. That exercise will help you learn the structure of C# code.
Your first program is limited to printing one message. You can write more useful programs by using variables. A variable is a symbol you can use to run the same code with different values. Let's try it! Replace the code you've written in the interactive window with the following code:
string aFriend = "Bill";
Console.WriteLine(aFriend);
The first line declares a variable, aFriend
, and assigns it a value, "Bill". The second line
prints out the name.
You can assign different values to any variable you declare. You can change
the name to one of your friends. Add these two lines in the interactive window
following the code you've already added. Make sure you keep the declaration
of the aFriend
variable and its initial assignment.
Important
Don't delete the declaration of aFriend
. Add the code below following the existing declaration.
aFriend = "Maira";
Console.WriteLine(aFriend);
Notice that the same line of code prints two different messages, based on
the value stored in the aFriend
variable.
You may have also noticed that the word "Hello" was missing in the last two messages. Let's fix that now. Modify the lines that print the message to the following:
Console.WriteLine("Hello " + aFriend);
Select Run again to see the results.
You've been using +
to build strings from variables and constant strings. There's a better way.
You can place a variable between {
and }
characters to tell C# to replace that text with the value of the variable.
This is called String interpolation.
If you add a $
before the opening quote of the string, you can then include variables, like aFriend
, inside the string between curly braces. Give it a try:
Console.WriteLine($"Hello {aFriend}");
Select Run again to see the results. Instead of "Hello {aFriend}", the message should be "Hello Maira".
Work with strings
Your last edit was our first look at what you can do with strings. Let's explore more.
You're not limited to a single variable between the curly braces. Try this:
string firstFriend = "Maria";
string secondFriend = "Sage";
Console.WriteLine($"My friends are {firstFriend} and {secondFriend}");
As you explore more with strings, you'll find that strings are more than a collection of letters. You can find the length of a string using Length
. Length
is a property of a string and it returns the number of characters in that string. Add the following code at the bottom of the interactive window:
Console.WriteLine($"The name {firstFriend} has {firstFriend.Length} letters.");
Console.WriteLine($"The name {secondFriend} has {secondFriend.Length} letters.");
Tip
This is a good time to explore on your own. You've learned that Console.WriteLine()
writes text to the screen. You've learned how to declare variables and
concatenate strings together. Experiment in the interactive window. The window has a feature called IntelliSense that
makes suggestions for what you can do. Type a .
after the d
in firstFriend
. You'll see a list of suggestions for properties
and methods you can use.
Do more with strings
You've been using a method, Console.WriteLine, to print messages. A method is a block of code that implements some action. It has a name, so you can access it.
Trim
Suppose your strings have leading or trailing spaces that you don't want to display. You want to trim the spaces from the strings. The Trim method and related methods TrimStart and TrimEnd do that work. You can just use those methods to remove leading and trailing spaces. Try the following code:
string greeting = " Hello World! ";
Console.WriteLine($"[{greeting}]");
string trimmedGreeting = greeting.TrimStart();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.TrimEnd();
Console.WriteLine($"[{trimmedGreeting}]");
trimmedGreeting = greeting.Trim();
Console.WriteLine($"[{trimmedGreeting}]");
The square brackets [
and ]
help visualize what the Trim
, TrimStart
and TrimEnd
methods do. The brackets show where whitespace starts and ends.
This sample reinforces a couple of important concepts for working with strings. The methods that manipulate strings return new string objects rather than making modifications in place. You can see that each call to any of the Trim
methods returns a new string but doesn't change the original message.
Replace
There are other methods available to work with a string. For example, you've probably used a search and replace command in an editor or word processor before. The Replace method does something similar in a string. It searches for a substring and replaces it with different text. The Replace method takes two parameters. These are the strings between the parentheses. The first string is the text to search for. The second string is the text to replace it with. Try it for yourself. Add this code. Type it in to see the hints as you start typing .Re
after the sayHello
variable:
string sayHello = "Hello World!";
Console.WriteLine(sayHello);
sayHello = sayHello.Replace("Hello", "Greetings");
Console.WriteLine(sayHello);
Two other useful methods make a string ALL CAPS or all lower case. Try the following code. Type it in to see how IntelliSense provides hints as you start to type To
:
Console.WriteLine(sayHello.ToUpper());
Console.WriteLine(sayHello.ToLower());
Search strings
The other part of a search and replace operation is to find text in a string. You can use the Contains method for searching. It tells you if a string contains a substring inside it. Try the following code to explore Contains:
string songLyrics = "You say goodbye, and I say hello";
Console.WriteLine(songLyrics.Contains("goodbye"));
Console.WriteLine(songLyrics.Contains("greetings"));
The Contains method returns a boolean value which tells you if the
string you were searching for was found. A boolean stores either a true
or a
false
value. When displayed as text output, they are capitalized: True
and False
, respectively. You'll learn more about boolean values
in a later lesson.
Challenge
There are two similar methods, StartsWith and EndsWith that also search for sub-strings in a string. These find a substring at the beginning or the end of the string. Try to modify the previous sample to use StartsWith and EndsWith instead of Contains. Search for "You" or "goodbye" at the beginning of a string. Search for "hello" or "goodbye" at the end of a string.
Note
Watch your punctuation when you test for the text at the end of the string. If the string ends with a period, you must check for a string that ends with a period.
You should get true
for starting with "You" and ending with "hello" and false
for starting with or ending with "goodbye".
Complete challenge
Did you come up with something like this?
string songLyrics = "You say goodbye, and I say hello";
Console.WriteLine(songLyrics.StartsWith("You"));
Console.WriteLine(songLyrics.StartsWith("goodbye"));
Console.WriteLine(songLyrics.EndsWith("hello"));
Console.WriteLine(songLyrics.EndsWith("goodbye"));
Congratulations!
You've completed the "Hello C#" introduction to C# tutorial. You can select the Numbers in C# link below to start the next interactive tutorial, or you can visit the .NET site to download the .NET SDK, create a project on your machine, and keep coding. The "Next steps" section brings you back to these tutorials.
For further reading on the string
type:
Have an issue with this section? If so, please give us some feedback so we can improve this section.
Feedback
https://aka.ms/ContentUserFeedback.
Coming soon: Throughout 2024 we will be phasing out GitHub Issues as the feedback mechanism for content and replacing it with a new feedback system. For more information see:Submit and view feedback for