Writing your first C# Program

Lesson 1.3: Writing Your First C# Program ("Hello, World!")


In this lesson, you'll create your first working C# program. It's a simple program that displays the message "Hello, World!" on the console (the text-based output window of your development environment).


Understanding the Code


Here's the C# code for our "Hello, World!" program:


C#

using System;


namespace HelloWorld

{

    class Program

    {

        static void Main(string[] args)

        {

            Console.WriteLine("Hello, World!");

        }

    }

}


Let's break down what each line means:


using System;


This line tells the compiler to include the System namespace. This namespace contains essential classes like Console, which we'll use to display our message.

namespace HelloWorld


Namespaces organize your code into logical groups. This line declares a namespace called HelloWorld to contain our program.

class Program


C# code is organized into classes. This line defines a class named Program, which will hold the instructions for our program.

static void Main(string[] args)


This is the Main method, the entry point of every C# program. The code within this method is what gets executed when you run your program.

static: This keyword means the method can be called without creating an object of the Program class.

void: This keyword indicates that the method doesn't return any value.

string[] args: This allows your program to receive command-line arguments, which we won't use in this example.

Console.WriteLine("Hello, World!");


This line is where the action happens! It tells the computer to:

Use the Console class (from the System namespace)

Call the WriteLine method

Pass the text "Hello, World!" as an argument to the WriteLine method, which will print the text to the console.

Writing and Running the Code


Create a New Project:


In Visual Studio: Go to File -> New -> Project. Choose "Console App (.NET Core)" or "Console App (.NET Framework)". Give your project a name (e.g., "HelloWorld") and click "Create".

In VS Code: Use the .NET CLI to create a console app:

Open a terminal.

Navigate to your desired directory.

Type dotnet new console --name HelloWorld and press Enter.

In any text editor: Create a new text file and save it as HelloWorld.cs

Write or Copy the Code:


Type or paste the "Hello, World!" code into the Program.cs file (or your created file).

Save the File: Make sure your file is saved.


Compile and Run:


In Visual Studio: Press the "Start" button or the F5 key to build and run your program.

In VS Code: Open a terminal within VS Code, navigate to the project folder, and type dotnet run then press Enter.

Output:


You should see the text "Hello, World!" displayed in the console window. Congratulations! You've just written and run your first C# program.

Course Syllabus