Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Writing Your First C# Program

Introduction to C#

C# (pronounced "C-sharp") is a modern, object-oriented programming language developed by Microsoft. It is widely used for building Windows applications, web applications, and games using the Unity game engine. In this tutorial, we will guide you through writing your first C# program from start to finish.

Setting Up Your Development Environment

Before you can write and run C# programs, you need to set up your development environment. We recommend using Visual Studio, which is a powerful integrated development environment (IDE) for C# development.

Follow these steps to set up your environment:

  1. Download and install Visual Studio from the official website.
  2. During installation, select the ".NET desktop development" workload.
  3. Once installed, open Visual Studio and create a new project.

Creating a New C# Project

Let's create a new C# project:

  1. Open Visual Studio.
  2. Select "Create a new project".
  3. Choose "Console App (.NET Core)" from the list of project templates.
  4. Click "Next", then provide a name and location for your project.
  5. Click "Create" to generate the project.

Writing Your First C# Program

Now that you have a new project, it's time to write your first C# program. Visual Studio will create a file named Program.cs by default. Open this file and you will see some boilerplate code:

using System;

namespace YourNamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello, World!");
        }
    }
}
                

Let's break down this code:

  • using System;: This line includes the System namespace, which contains fundamental classes and base classes that define commonly-used values and reference data types.
  • namespace YourNamespace: Namespaces are used to organize code and prevent naming conflicts.
  • class Program: This is the class definition. Every C# program must have at least one class.
  • static void Main(string[] args): This is the Main method, which is the entry point of a C# console application. The string[] args parameter is used to capture command-line arguments.
  • Console.WriteLine("Hello, World!");: This line prints "Hello, World!" to the console.

Running Your Program

To run your program, follow these steps:

  1. Click on the "Start" button in Visual Studio, or press F5.
  2. The console window will appear and display "Hello, World!".

You should see an output similar to this:

Hello, World!

Exploring Further

Congratulations! You've written and run your first C# program. Here are a few suggestions for what to try next:

  • Modify the Console.WriteLine line to print different messages.
  • Add more lines of code to perform calculations or take user input.
  • Explore other features of C# such as loops, conditionals, and methods.

Happy coding!