1.5 - Your First C# Program: "Hello, World!"
Now that your development environment is set up, it's time to write your first C# program! We'll start with the traditional "Hello, World!" program, which simply displays a greeting message. This simple program will help you understand the basic structure of C# code.
Creating a New Console Application
If you haven't already created a project in the previous section, let's do that now:
Using Visual Studio
- Open Visual Studio
- Click "Create a new project"
- Select "Console App (.NET Core)" or "Console App (.NET)" template
- Name your project "HelloWorld"
- Choose a location to save your project
- Click "Create"
Using VS Code and .NET CLI
- Open a terminal or command prompt
- Navigate to the directory where you want to create your project
- Run the following commands:
# Create a new console application
dotnet new console -n HelloWorld
# Navigate to the project directory
cd HelloWorld
# Open the project in VS Code
code .
Understanding the Generated Code
When you create a new console application, your IDE generates some starter code. Let's examine it:
Modern C# 9+ Template (Top-level statements)
If you're using the latest .NET SDK, you might see something like this:
// Program.cs
Console.WriteLine("Hello, World!");
This is using a C# 9 feature called "top-level statements" which allows you to write code directly without the traditional boilerplate. While this is convenient for quick console applications, Unity scripts typically use the traditional class structure, so we'll focus on that.
Traditional Class Structure
For Unity development, it's important to understand the traditional class structure. Let's modify our program to use this approach:
// Program.cs
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
}
Let's break down this code:
-
using System;
: This is a directive that tells the compiler to include the System namespace, which contains fundamental classes like Console. -
namespace HelloWorld
: A namespace is a way to organize code and prevent name conflicts. Here, we're declaring that our code belongs to the HelloWorld namespace. -
class Program
: This defines a class named Program. In C#, all code must be contained within a class (except for top-level statements in C# 9+). -
static void Main(string[] args)
: This is the entry point of our application—the method that gets called when the program starts.static
: The method belongs to the class itself, not to instances of the class.void
: The method doesn't return any value.Main
: The name of the method. The entry point must be named Main.string[] args
: An array of strings that can contain command-line arguments.
-
Console.WriteLine("Hello, World!");
: This line actually does the work—it prints the text "Hello, World!" to the console.
Running Your First Program
Now let's run the program to see it in action:
In Visual Studio
- Press F5 to run the program in debug mode, or Ctrl+F5 to run without debugging.
- You should see a console window appear with the text "Hello, World!".
In VS Code
- Open the integrated terminal (View > Terminal or Ctrl+`).
- Run the command:
dotnet run
. - You should see the output "Hello, World!" in the terminal.
Congratulations! You've just written and executed your first C# program.
Modifying the Program
Let's make a few changes to our program to learn more about C# syntax:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Display a welcome message
Console.WriteLine("Hello, World!");
// Wait for user input before displaying the next message
Console.WriteLine("Press any key to continue...");
Console.ReadKey();
// Display a farewell message
Console.WriteLine("Thank you for running my first C# program!");
}
}
}
New elements in this code:
-
Comments: Lines starting with
//
are comments. They're ignored by the compiler and are used to explain the code. -
Console.ReadKey()
: This method waits for the user to press a key before continuing. -
Multiple statements: We've added more lines of code that execute sequentially from top to bottom.
Run the program again to see the changes.
Making It More Interactive
Let's modify our program to make it interactive by asking for the user's name:
using System;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Ask for the user's name
Console.WriteLine("What is your name?");
// Read the user's input
string userName = Console.ReadLine();
// Display a personalized greeting
Console.WriteLine("Hello, " + userName + "!");
// Wait for user input before exiting
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}
New elements in this code:
-
Console.ReadLine()
: This method reads a line of text from the console (i.e., what the user types until they press Enter). -
string userName
: This declares a variable nameduserName
of typestring
to store the user's input. -
String concatenation: The
+
operator is used to combine (concatenate) strings.
Run the program and enter your name when prompted.
Using String Interpolation (C# 6+)
C# 6 introduced a more elegant way to insert values into strings called string interpolation. Let's update our greeting to use this feature:
// Display a personalized greeting using string interpolation
Console.WriteLine($"Hello, {userName}!");
The $
symbol before the string and the curly braces {}
around the variable name tell C# to replace the variable with its value.
Compiling and Running: Behind the Scenes
When you run your C# program, several things happen behind the scenes:
-
Compilation: The C# compiler converts your source code (.cs files) into Intermediate Language (IL) code.
-
Assembly Creation: The IL code is packaged into an assembly (.dll or .exe file).
-
Execution: The Common Language Runtime (CLR) loads the assembly and converts the IL code to native machine code through Just-In-Time (JIT) compilation.
-
Program Execution: The native code runs on your computer.
Common Errors and How to Fix Them
As you write more code, you'll inevitably encounter errors. Here are some common ones:
-
Syntax Errors: Missing semicolons, brackets, or typos.
Console.WriteLine("Hello, World") // Missing semicolon
-
Runtime Errors: Errors that occur while the program is running, like trying to divide by zero.
int result = 10 / 0; // Will cause a DivideByZeroException
-
Logical Errors: The program runs but doesn't do what you expect.
// Meant to add 2 numbers but accidentally used string concatenation
Console.WriteLine("5" + "10"); // Outputs "510" instead of "15"
When you encounter errors, read the error message carefully—it often tells you exactly what's wrong and where to look.
Conclusion
Congratulations! You've written your first C# program and learned about the basic structure of C# code. You've also made your program interactive and learned about string manipulation.
In the next section, we'll explore code comments in more detail and discuss best practices for writing readable code.
While Unity scripts have a different structure (they typically inherit from MonoBehaviour
and don't have a Main
method), the C# syntax and concepts you're learning here—variables, methods, string manipulation, etc.—are exactly the same in Unity.
In Unity, instead of Console.WriteLine()
, you'll often use Debug.Log()
to output messages to Unity's Console window.