Skip to main content

C# First Program

Introduction​

Welcome to the exciting world of C# programming! In this tutorial, we'll create your very first C# program - the classic "Hello World" application. This simple program serves as the traditional starting point for learning any programming language and will help you understand the basic structure of C# applications.

By the end of this guide, you'll have written, compiled, and executed your first C# program, and you'll understand each component that makes it work.

Prerequisites​

Before we begin, make sure you have:

  • .NET SDK installed on your computer
  • A code editor (Visual Studio, Visual Studio Code, or any text editor)

Creating Your First C# Program​

Step 1: Setting Up Your Project​

Let's start by creating a new console application. If you're using Visual Studio, you can:

  1. Open Visual Studio
  2. Select "Create a new project"
  3. Choose "Console App (.NET Core)" or "Console App (.NET)"
  4. Name your project "HelloWorld"

If you prefer using the command line:

bash
dotnet new console -n HelloWorld
cd HelloWorld

Step 2: Understanding the Generated Code​

Open the Program.cs file. Depending on your .NET version, you'll see one of these two versions:

For .NET 5 and earlier:

csharp
using System;

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

For .NET 6 and newer:

csharp
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello World!");

Let's stick with the more explicit first version for better understanding.

Step 3: Analyzing the Code Structure​

Let's break down the components of our program:

  1. Using Directive:

    csharp
    using System;

    This line tells the compiler that we're using the System namespace, which contains fundamental classes like Console.

  2. Namespace Declaration:

    csharp
    namespace HelloWorld
    {
    // Code here
    }

    Namespaces organize code and prevent naming conflicts. Here, our code belongs to the HelloWorld namespace.

  3. Class Declaration:

    csharp
    class Program
    {
    // Methods here
    }

    In C#, code is organized into classes. Program is the main class of our application.

  4. Main Method:

    csharp
    static void Main(string[] args)
    {
    // Code to execute
    }

    Every C# console application needs a Main method. It's the entry point - the first code that runs when your 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 (must be spelled exactly like this)
    • string[] args: Command-line arguments passed to the program
  5. Program Logic:

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

    This line prints "Hello World!" to the console window. Console is a class, and WriteLine is a method that outputs text followed by a new line.

Step 4: Running Your Program​

To run your program:

  • In Visual Studio: Press F5 or click "Start Debugging"
  • In the command line: Type dotnet run

Output:

Hello World!

Congratulations! You've just created and run your first C# program.

Modifying Your First Program​

Let's make our program a bit more interactive:

csharp
using System;

namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
// Prompt the user for their name
Console.Write("Please enter your name: ");

// Read the user's input
string name = Console.ReadLine();

// Display a personalized greeting
Console.WriteLine($"Hello, {name}! Welcome to the world of C#!");

// Wait for a key press before closing
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
}
}

Example Interaction:

Please enter your name: Sarah
Hello, Sarah! Welcome to the world of C#!
Press any key to exit...

Explanation of New Elements:​

  1. Console.Write(): Similar to WriteLine() but doesn't add a new line after the text
  2. Console.ReadLine(): Reads a line of text from the console
  3. string name: Declares a variable that stores the user's input
  4. $"Hello, {name}!": String interpolation - a convenient way to insert variable values into strings
  5. Console.ReadKey(): Waits for the user to press a key before continuing

Practical Application: Simple Calculator​

Let's build a simple calculator to demonstrate how you can create useful programs right from the start:

csharp
using System;

namespace SimpleCalculator
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Simple Calculator");
Console.WriteLine("-----------------");

// Get first number
Console.Write("Enter first number: ");
double num1 = Convert.ToDouble(Console.ReadLine());

// Get second number
Console.Write("Enter second number: ");
double num2 = Convert.ToDouble(Console.ReadLine());

// Display results of operations
Console.WriteLine($"{num1} + {num2} = {num1 + num2}");
Console.WriteLine($"{num1} - {num2} = {num1 - num2}");
Console.WriteLine($"{num1} * {num2} = {num1 * num2}");

// Handle division by zero
if (num2 != 0)
{
Console.WriteLine($"{num1} / {num2} = {num1 / num2}");
}
else
{
Console.WriteLine("Cannot divide by zero.");
}

Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
}

Example Interaction:

Simple Calculator
-----------------
Enter first number: 10
Enter second number: 5
10 + 5 = 15
10 - 5 = 5
10 * 5 = 50
10 / 5 = 2

Press any key to exit...

This calculator demonstrates several important concepts:

  • Getting user input and converting it to appropriate data types
  • Performing basic arithmetic operations
  • Implementing basic logic with if/else statements
  • Formatting output for readability

Common Errors and Troubleshooting​

When writing your first C# programs, you might encounter these common issues:

  1. Syntax Errors: Missing semicolons, brackets, or typos in keywords

    csharp
    Console.WriteLine("Hello World")  // Missing semicolon
  2. Runtime Errors: Issues that occur when the program runs

    csharp
    // This will crash if the user enters non-numeric text
    int number = Convert.ToInt32(Console.ReadLine());
  3. Logic Errors: The program runs but produces incorrect results

    csharp
    // Intended to add, but using wrong operator
    int result = 5 * 10; // Gives 50 instead of 15

Summary​

In this tutorial, you've learned:

  • How to create a basic C# console application
  • The structure and components of a C# program
  • How to get input from users and display output
  • How to implement a simple interactive calculator

You've taken your first steps into the vast world of C# programming! From this foundation, you can start building more complex and useful applications.

Additional Resources​

Practice Exercises​

  1. Modify the Hello World program to ask for the user's age and display how old they will be in 10 years.
  2. Create a program that converts temperatures between Fahrenheit and Celsius.
  3. Build a simple quiz program that asks multiple-choice questions and keeps score.

Happy coding!



If you spot any mistakes on this website, please let me know at feedback@compilenrun.com. I’d greatly appreciate your feedback! :)