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:
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:
# Windows
cd C:\Users\YourName\Projects
# macOS/Linux
cd ~/Projects
Now create a new console application:
dotnet new console -n HelloWorld
dotnet new = Create a new project
console = Use the console application template
-n HelloWorld = Name the project "HelloWorld"
You'll see output like:
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:
cd HelloWorld
Step 2: Explore What Was Created
List the files in your project directory:
# Windows (PowerShell)
dir
# macOS/Linux
ls -la
You'll see:
Program.cs- Your C# source code fileHelloWorld.csproj- Project configuration fileobj/- Build artifacts (auto-generated)
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:
// 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.
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:
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):
dotnet run
You'll see:
Hello, World!
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?
- Compilation: C# compiler (Roslyn) compiled
Program.csto Intermediate Language (IL) - Output: Created
HelloWorld.dllin thebin/Debug/net8.0/folder - Execution: .NET Runtime loaded the DLL and executed your code
- 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:
// 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:
dotnet run
Now it's interactive! Try it:
Welcome to .NET!
==================
What's your name? John
Hello, John! Welcome to your .NET journey!
You're running .NET 8.0.0
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:
// 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:
dotnet run
You'll see a beautiful, color-coded inventory report:
ββββββββββββββββββββββββββββββββββββββ
β 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
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
# Build only (compile, don't run)
dotnet build
# Build and run
dotnet run
When you run dotnet build, you'll see:
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 informationHelloWorld.runtimeconfig.json- Runtime configuration
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
- Open Visual Studio
- Click "Open a project or solution"
- Navigate to your project folder
- Select
HelloWorld.csproj - 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
- Open VS Code
- Click "File" β "Open Folder"
- Select your
HelloWorldfolder - 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 |
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 runbuilds and executes your applicationdotnet buildcompiles without running- Compiled output goes to
bin/Debug/net8.0/ - String interpolation (
$"...") embeds variables in strings Console.WriteLine()prints outputConsole.ReadLine()reads user input- You can change console colors with
Console.ForegroundColor - Use
int.TryParse()to safely convert strings to numbers
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.