Skip to content

First C# Program

This chapter will guide you through creating and running your first C# program, understanding the basic structure of C# programs, and mastering the basic compilation and execution process.

Hello World Program

Creating the Project

Creating with Visual Studio

  1. Launch Visual Studio
  2. Select "Create new project"
  3. Choose "Console App" template
  4. Configure project information:
    Project name: HelloWorld
    Location: C:\CSharpProjects
    Solution name: HelloWorld
    Framework: .NET 8.0

Creating with Command Line

powershell
# Create project directory
mkdir HelloWorld
cd HelloWorld

# Create console application project
dotnet new console

# View generated files
dir

Program Code

Visual Studio automatically generates the following code:

csharp
// Program.cs
using System;

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

Understanding the Code Structure

Let's analyze each part of the program:

1. using Directive

csharp
using System;
  • Purpose: Import the System namespace
  • System namespace: Contains fundamental classes like Console
  • using: Allows access to types without full namespace qualification

2. Namespace Declaration

csharp
namespace HelloWorld
{
    // Code inside namespace
}
  • Namespace: Organizes code into logical groups
  • HelloWorld: Custom namespace name
  • Purpose: Prevents naming conflicts

3. Class Declaration

csharp
class Program
{
    // Class members
}
  • Class: Blueprint for creating objects
  • Program: Entry point class name
  • Purpose: Contains the Main method

4. Main Method

csharp
static void Main(string[] args)
{
    // Program execution starts here
}
  • static: Method belongs to class, not instance
  • void: Method returns no value
  • Main: Entry point of the program
  • string[] args: Command line arguments

Running the Program

Using Visual Studio

  1. Build the project: Press F6 or Build → Build Solution
  2. Run the program: Press F5 or Debug → Start Debugging
  3. View output: Console window will show "Hello World!"

Using Command Line

powershell
# Build the project
dotnet build

# Run the program
dotnet run

Output

Hello World!

Program Variations

Different Output Messages

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Welcome to C# Programming!");
            Console.WriteLine("This is my first C# program.");
            Console.WriteLine("Let's start learning C#!");
        }
    }
}

Using String Interpolation

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            string name = "C#";
            int version = 12;
            
            Console.WriteLine($"Hello {name} version {version}!");
        }
    }
}

Reading User Input

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Please enter your name: ");
            string name = Console.ReadLine();
            
            Console.WriteLine($"Hello, {name}! Welcome to C# programming.");
        }
    }
}

Command Line Arguments

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"Number of arguments: {args.Length}");
            
            for (int i = 0; i < args.Length; i++)
            {
                Console.WriteLine($"Argument {i}: {args[i]}");
            }
        }
    }
}

Run with arguments:

powershell
dotnet run -- arg1 arg2 arg3

Output:

Number of arguments: 3
Argument 0: arg1
Argument 1: arg2
Argument 2: arg3

Modern C# Features

Top-Level Statements (C# 9.0+)

csharp
// Simplified version without explicit class and Main
using System;

Console.WriteLine("Hello World with top-level statements!");

string name = "C#";
Console.WriteLine($"Welcome to {name}!");

Global Using Directives (C# 10.0+)

csharp
// Program.cs
global using System;

Console.WriteLine("Hello World!");
Console.WriteLine("No need for 'using System;' in every file.");

Implicit Usings (C# 10.0+)

csharp
// Console app automatically includes common namespaces
Console.WriteLine("Hello World!");
// No explicit 'using System;' needed

Compilation Process

What Happens When You Build

  1. Source Code: Your .cs files
  2. Compilation: C# compiler (csc.exe) converts to IL
  3. Intermediate Language: Platform-independent bytecode
  4. JIT Compilation: Just-In-Time compiler converts to machine code
  5. Execution: Machine code runs on target platform

Build Commands

powershell
# Build project
dotnet build

# Build for specific configuration
dotnet build --configuration Release

# Build for specific framework
dotnet build --framework net8.0

# Clean build artifacts
dotnet clean

Debugging Basics

Setting Breakpoints

  1. Click in margin: Click left margin of code line
  2. Press F9: Place cursor on line and press F9
  3. Conditional breakpoints: Right-click breakpoint → Condition

Debugging Steps

  1. Start debugging: Press F5
  2. Step over: Press F10 (execute current line)
  3. Step into: Press F11 (enter method)
  4. Continue: Press F5 (run to next breakpoint)

Debug Windows

  • Autos: Variables used in current and previous lines
  • Locals: Variables in current scope
  • Watch: Custom expressions to monitor
  • Call Stack: Method call hierarchy

Common Errors and Solutions

Syntax Errors

csharp
// Missing semicolon
Console.WriteLine("Hello World")  // Error: ; expected

// Fix
Console.WriteLine("Hello World");  // Correct

Compilation Errors

csharp
// Undefined variable
string message;
Console.WriteLine(mesage);  // Error: 'mesage' does not exist

// Fix
string message;
Console.WriteLine(message);  // Correct

Runtime Errors

csharp
// Null reference
string text = null;
Console.WriteLine(text.Length);  // Error: NullReferenceException

// Fix
string text = null;
if (text != null)
{
    Console.WriteLine(text.Length);
}

Best Practices

Code Organization

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            // Clear separation of concerns
            DisplayWelcomeMessage();
            ProcessUserInput();
        }
        
        static void DisplayWelcomeMessage()
        {
            Console.WriteLine("Welcome to C# Programming!");
        }
        
        static void ProcessUserInput()
        {
            Console.Write("Enter your name: ");
            string name = Console.ReadLine();
            Console.WriteLine($"Hello, {name}!");
        }
    }
}

Error Handling

csharp
using System;

namespace HelloWorld
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                Console.Write("Enter a number: ");
                string input = Console.ReadLine();
                int number = int.Parse(input);
                Console.WriteLine($"You entered: {number}");
            }
            catch (FormatException)
            {
                Console.WriteLine("Invalid number format!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error: {ex.Message}");
            }
        }
    }
}

Summary

In this chapter, you learned:

  • How to create a C# console application
  • Basic structure of a C# program
  • Key components: using directives, namespaces, classes, methods
  • How to compile and run C# programs
  • Modern C# features like top-level statements
  • Basic debugging techniques
  • Common errors and how to fix them

The Hello World program is your first step into C# programming. In the next chapter, we'll explore C# basic syntax in detail, including variables, data types, and operators.

Content is for learning and research only.