Labs ICT
โญ Pro Login

Your First C# Program

Alright, let us write some code. This is the fun part. We are going to create a simple console application that prints "Hello, World!" to the screen. Classic, right?

Open your terminal and run these commands:

dotnet new console -n HelloWorld
cd HelloWorld
dotnet run

Let me break down what just happened. The first command creates a new console project called "HelloWorld". The second command moves you into that project folder. And the third command compiles and runs your application.

You should see "Hello, World!" printed on your screen. Congratulations โ€” you just wrote your first C# program. That was not so hard, was it?

What Does the Code Look Like?

Open the project folder in your code editor. You will see a file called Program.cs. Let us look at what is inside:

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

That is it. One line of code. And yet, there is actually a lot happening behind the scenes. Let me explain.

  • Console is a class that handles input and output for console applications.
  • WriteLine is a method that prints text to the screen and then moves to the next line.
  • The text inside the quotes is called a string โ€” it is just a sequence of characters.
  • The semicolon at the end tells C# that this statement is complete.

Understanding the Project Structure

When you created the project, .NET generated a few files for you. The most important one is the .csproj file. Think of it as a configuration file that tells .NET how to build your project. It specifies things like the target framework and any packages your project needs.

You will also notice a bin and obj folder. These are created when you build your project. They contain the compiled code and temporary files. You do not need to worry about them for now.

Adding More Code

Let us make things a little more interesting. Try replacing the content of Program.cs with this:

Console.WriteLine("What is your name?");
string name = Console.ReadLine();
Console.WriteLine("Hello, " + name + "! Welcome to .NET!");

Run it again with dotnet run. This time, it asks for your name, waits for you to type something, and then greets you personally. You just built your first interactive program.

Notice the string name = Console.ReadLine(); part. This is how you read input from the user. The ReadLine method waits for the user to press Enter and returns whatever they typed as a string.

Try it yourself and see how it works. In the next lesson, we will dive deeper into variables and data types.

๐Ÿงช Quick Quiz

What does Console.WriteLine() do?