Section 3 of 6

Your First Console Application

🎯 What You'll Learn

  • Creating a console app with the dotnet CLI
  • Understanding the generated project structure
  • Writing your first C# code
  • Building and running your application
  • Understanding top-level statements
  • Adding more functionality to your app
  • Creating a simple InvenTrack inventory checker

The Development Workflow

Every .NET application follows this workflow:

Development Workflow Process
1. Create Project    β†’ dotnet new
2. Write Code        β†’ Edit .cs files
3. Build             β†’ dotnet build (compile C# to IL)
4. Run               β†’ dotnet run (execute your app)
5. Test & Debug      β†’ Fix issues, repeat 2-4
6. Publish           β†’ dotnet publish (deploy)

Let's walk through this entire process step by step!

Step 1: Create Your First Project

Open a terminal (Command Prompt, PowerShell, or Terminal) and navigate to where you want to create your project. For example:

Terminal Shell
# Windows
cd C:\Users\YourName\Projects

# macOS/Linux
cd ~/Projects

Now create a new console application:

Terminal Shell
dotnet new console -n HelloWorld
ℹ️ Command Breakdown

dotnet new = Create a new project
console = Use the console application template
-n HelloWorld = Name the project "HelloWorld"

You'll see output like:

Output Text
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring C:\Users\YourName\Projects\HelloWorld\HelloWorld.csproj:
  Determining projects to restore...
  Restored C:\Users\YourName\Projects\HelloWorld\HelloWorld.csproj (in 234 ms).
Restore succeeded.

Navigate into your new project:

Terminal Shell
cd HelloWorld

Step 2: Explore What Was Created

List the files in your project directory:

Terminal Shell
# Windows (PowerShell)
dir

# macOS/Linux
ls -la

You'll see:

  • Program.cs - Your C# source code file
  • HelloWorld.csproj - Project configuration file
  • obj/ - Build artifacts (auto-generated)
πŸ’‘ What's What?

Program.cs: Where you write your C# code
.csproj: Project file (like package.json for Node.js)
obj/: Temporary build files (ignore this folder)

Step 3: Look at the Generated Code

Open Program.cs in any text editor. You'll see:

Program.cs C#
// See https://aka.ms/new-console-template for more information
Console.WriteLine("Hello, World!");

That's it! Just one line of code. This is called a top-level statementβ€”a simplified syntax introduced in C# 9 that removes boilerplate code.

πŸ’‘ Top-Level Statements

In older C# versions, you needed a Main method inside a class. Modern C# lets you skip that and write code directly. The compiler automatically wraps your code in a Main method behind the scenes.

Traditional vs Modern Syntax

Here's what the same program looks like in traditional C# syntax:

Traditional Syntax (C# 8 and earlier) C#
using System;

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

Both do the exact same thing! Modern C# just removes the ceremony.

Step 4: Run Your Application

Let's run the app! In your terminal (make sure you're in the HelloWorld directory):

Terminal Shell
dotnet run

You'll see:

Output Text
Hello, World!
πŸŽ‰ Congratulations!

You just created, compiled, and ran your first .NET application! The dotnet run command automatically builds your project and executes it.

What Happened Behind the Scenes?

  1. Compilation: C# compiler (Roslyn) compiled Program.cs to Intermediate Language (IL)
  2. Output: Created HelloWorld.dll in the bin/Debug/net8.0/ folder
  3. Execution: .NET Runtime loaded the DLL and executed your code
  4. Result: "Hello, World!" printed to the console

Step 5: Modify Your Application

Let's make it more interesting! Open Program.cs and replace the content with:

Program.cs C#
// Welcome message
Console.WriteLine("Welcome to .NET!");
Console.WriteLine("==================\n");

// Get user's name
Console.Write("What's your name? ");
string? name = Console.ReadLine();

// Greet the user
Console.WriteLine($"\nHello, {name}! Welcome to your .NET journey!");

// Show .NET version
Console.WriteLine($"You're running .NET {Environment.Version}");

Run it again:

Terminal Shell
dotnet run

Now it's interactive! Try it:

Output Text
Welcome to .NET!
==================

What's your name? John
Hello, John! Welcome to your .NET journey!
You're running .NET 8.0.0
πŸ’‘ New Concepts Used

Console.Write() - Prints without a newline
Console.ReadLine() - Reads user input
string? - Nullable string (can be null)
$"..." - String interpolation (embed variables)
Environment.Version - Get .NET runtime version

Step 6: Build a Simple InvenTrack Inventory Checker

Let's create something more practicalβ€”a simple inventory checker for InvenTrack! Replace Program.cs with:

Program.cs C#
// InvenTrack - Simple Inventory Checker
Console.WriteLine("╔════════════════════════════════════╗");
Console.WriteLine("β•‘   InvenTrack Inventory Checker    β•‘");
Console.WriteLine("β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•\n");

// Sample inventory data
string productName = "Laptop - Dell XPS 15";
string sku = "LAP-DELL-XPS15";
int quantityInStock = 15;
decimal unitPrice = 1299.99m;
int reorderLevel = 10;

// Display product information
Console.WriteLine("Product Information:");
Console.WriteLine("--------------------");
Console.WriteLine($"Name:     {productName}");
Console.WriteLine($"SKU:      {sku}");
Console.WriteLine($"Price:    ${unitPrice:N2}");
Console.WriteLine($"In Stock: {quantityInStock} units\n");

// Calculate total value
decimal totalValue = quantityInStock * unitPrice;
Console.WriteLine($"Total Inventory Value: ${totalValue:N2}\n");

// Check stock status
Console.WriteLine("Stock Status:");
Console.WriteLine("-------------");

if (quantityInStock == 0)
{
    Console.ForegroundColor = ConsoleColor.Red;
    Console.WriteLine("⚠️  OUT OF STOCK - Reorder immediately!");
}
else if (quantityInStock <= reorderLevel)
{
    Console.ForegroundColor = ConsoleColor.Yellow;
    Console.WriteLine($"⚠️  LOW STOCK - Only {quantityInStock} units remaining");
    Console.WriteLine($"   Consider reordering (threshold: {reorderLevel} units)");
}
else
{
    Console.ForegroundColor = ConsoleColor.Green;
    Console.WriteLine("βœ“ Stock levels are healthy");
}

// Reset console color
Console.ResetColor();

// Interactive: Check another product
Console.WriteLine("\n--------------------");
Console.Write("Enter quantity to check: ");
string? input = Console.ReadLine();

if (int.TryParse(input, out int checkQuantity))
{
    decimal value = checkQuantity * unitPrice;
    Console.WriteLine($"\n{checkQuantity} units would be worth: ${value:N2}");
}
else
{
    Console.WriteLine("\nInvalid quantity entered.");
}

Run it:

Terminal Shell
dotnet run

You'll see a beautiful, color-coded inventory report:

Output Text
╔════════════════════════════════════╗
β•‘   InvenTrack Inventory Checker    β•‘
β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•

Product Information:
--------------------
Name:     Laptop - Dell XPS 15
SKU:      LAP-DELL-XPS15
Price:    $1,299.99
In Stock: 15 units

Total Inventory Value: $19,499.85

Stock Status:
-------------
⚠️  LOW STOCK - Only 15 units remaining
   Consider reordering (threshold: 10 units)

--------------------
Enter quantity to check: 50

50 units would be worth: $64,999.50
πŸš€ What You Just Built!

This simple console app demonstrates:
β€’ Variables and data types
β€’ String interpolation and formatting
β€’ Arithmetic operations
β€’ Conditional logic (if/else)
β€’ Console colors for visual feedback
β€’ User input and validation
β€’ Number parsing with TryParse

Understanding the Build Process

dotnet run vs dotnet build

Terminal Shell
# Build only (compile, don't run)
dotnet build

# Build and run
dotnet run

When you run dotnet build, you'll see:

Output Text
MSBuild version 17.8.0+b89cb5fde for .NET
  Determining projects to restore...
  All projects are up-to-date for restore.
  HelloWorld -> C:\Projects\HelloWorld\bin\Debug\net8.0\HelloWorld.dll

Build succeeded.
    0 Warning(s)
    0 Error(s)

Where's the Output?

After building, check the bin/Debug/net8.0/ folder:

  • HelloWorld.dll - Your compiled application (IL code)
  • HelloWorld.exe - Windows launcher (on Windows only)
  • HelloWorld.deps.json - Dependency information
  • HelloWorld.runtimeconfig.json - Runtime configuration
ℹ️ Running the Compiled App Directly

You can run the compiled DLL directly:
dotnet bin/Debug/net8.0/HelloWorld.dll
Or on Windows, just double-click HelloWorld.exe

Opening Your Project in an IDE

Visual Studio 2022

  1. Open Visual Studio
  2. Click "Open a project or solution"
  3. Navigate to your project folder
  4. Select HelloWorld.csproj
  5. Click "Open"

Now you can edit, build, and run from within Visual Studio. Press F5 to run with debugging, or Ctrl+F5 to run without debugging.

Visual Studio Code

  1. Open VS Code
  2. Click "File" β†’ "Open Folder"
  3. Select your HelloWorld folder
  4. VS Code will detect the C# project and offer to add build assetsβ€”click "Yes"

Press F5 to run with debugging.

Common Commands Reference

Command What It Does
dotnet new console -n MyApp Create a new console application
dotnet run Build and run the application
dotnet build Compile the application
dotnet clean Delete build artifacts (bin/obj folders)
dotnet watch run Run and auto-restart on file changes
dotnet publish Prepare app for deployment
πŸ’‘ Hot Reload with dotnet watch

Try dotnet watch run! It automatically rebuilds and restarts your app whenever you save changes to your code. Perfect for rapid development!

Key Takeaways

  • Create projects with dotnet new console -n ProjectName
  • Program.cs contains your C# code
  • Top-level statements simplify console apps (no Main method needed)
  • dotnet run builds and executes your application
  • dotnet build compiles without running
  • Compiled output goes to bin/Debug/net8.0/
  • String interpolation ($"...") embeds variables in strings
  • Console.WriteLine() prints output
  • Console.ReadLine() reads user input
  • You can change console colors with Console.ForegroundColor
  • Use int.TryParse() to safely convert strings to numbers
🎯 Next Steps

You've created and run your first .NET application! In the next section, we'll dive deeper into project files and structureβ€”understanding what the .csproj file does, how dependencies work, and how to configure your projects.