Table of Contents
- Prerequisites
- Setting Up Your Development Environment
- Creating Your First C# Project
- Understanding the Project Structure
- Writing Your First C# Code
- Building and Running the Project
- Debugging Basics
- Adding Dependencies with NuGet
- Advanced Topics (Optional)
- Conclusion
- References
Prerequisites
Before we start, ensure you have the following:
- .NET SDK: The Software Development Kit (SDK) includes tools to build, run, and publish C# projects. We’ll use .NET 8 (LTS, Long-Term Support) for this tutorial.
- An IDE (Integrated Development Environment): Options include:
- Visual Studio 2022 (Windows, free Community edition available).
- Visual Studio Code (cross-platform, with the C# extension).
- JetBrains Rider (cross-platform, paid with a free trial).
- Basic Programming Knowledge: Familiarity with concepts like variables, functions, and classes will help, but beginners can still follow along.
Setting Up Your Development Environment
Installing the .NET SDK
- Download the SDK:
Visit the .NET 8 download page and select the installer for your OS (Windows, macOS, or Linux). - Run the Installer:
Follow the on-screen prompts. For Windows, ensure “Add to PATH” is checked. - Verify Installation:
Open a terminal/command prompt and run:
You should see output likedotnet --version8.0.100(version numbers may vary slightly).
Choosing an IDE
Option 1: Visual Studio 2022 (Windows)
- Download the Visual Studio Community edition.
- During installation, select the “.NET Desktop Development” workload (this includes tools for C# development).
Option 2: Visual Studio Code (Cross-Platform)
- Install VS Code.
- Install the C# extension by Microsoft (search for “C#” in the Extensions tab).
Option 3: JetBrains Rider
- Download Rider and follow the installation steps. It includes built-in support for .NET and C#.
Creating Your First C# Project
We’ll create a simple console application (runs in a terminal) using two methods: the .NET CLI (command line) and an IDE (we’ll use Visual Studio 2022 as an example).
Using the .NET CLI (Command-Line Interface)
The .NET CLI is a powerful tool for managing C# projects without an IDE. Here’s how to use it:
-
Open a Terminal:
On Windows, use Command Prompt or PowerShell; on macOS/Linux, use Terminal. -
Create a Project Directory:
Navigate to where you want to store your project (e.g.,Documents), then create a folder and enter it:mkdir CSharpFirstProject cd CSharpFirstProject -
Create a Console App:
Run the following command to generate a new console application project:dotnet new consoleThe
dotnet newcommand creates a project from a template (consoleis the template name for console apps). -
Verify the Project:
You’ll see output confirming the project was created. List the files in the directory:dir # Windows ls # macOS/LinuxYou should see:
Program.cs: The main code file.CSharpFirstProject.csproj: The project configuration file.
Using an IDE (Visual Studio Example)
If you prefer a graphical interface, here’s how to create a project in Visual Studio 2022:
-
Open Visual Studio and click “Create a new project”.
-
Select a Template:
Search for “Console App (.NET)” and select it. Click “Next”. -
Configure Project:
- Project name: Enter
CSharpFirstProject. - Location: Choose a folder to save the project.
- Framework: Select
.NET 8.0 (LTS).
Click “Create”.
- Project name: Enter
Visual Studio will generate the same files as the CLI method: Program.cs and CSharpFirstProject.csproj.
Understanding the Project Structure
Let’s explore the key components of your new C# project:
The .csproj File
The .csproj (C# Project) file is an XML document that defines your project’s settings, dependencies, and build configuration. Open it in a text editor or IDE to see its contents:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
- Sdk: Specifies the .NET SDK version (e.g.,
Microsoft.NET.Sdkfor console apps). - OutputType:
Exemeans the project builds an executable (.exeon Windows, a binary on macOS/Linux). - TargetFramework: The .NET runtime version (here,
.NET 8.0). - ImplicitUsings: Automatically includes common namespaces (e.g.,
System), reducing boilerplate. - Nullable: Enables nullable reference types (helps prevent null reference errors).
Key Files and Folders
-
Program.cs: The entry point of your application. By default, it contains:
// See https://aka.ms/new-console-template for more information Console.WriteLine("Hello, World!");This is a “top-level statement” (introduced in C# 9), which simplifies the syntax by omitting the traditional
Mainmethod and namespace. -
obj/: Contains intermediate build outputs (e.g., compiled code, temporary files).
-
bin/: Contains the final build output (executable, libraries, etc.). This folder is created when you build the project.
Writing Your First C# Code
Let’s modify the default Program.cs to make it more interactive.
Hello World: The Default Template
Run the project now to see the default output. Using the CLI:
dotnet run
You’ll see:
Hello, World!
Expanding the Code: Adding Logic
Let’s enhance the app to ask for the user’s name and greet them. Update Program.cs as follows:
// Prompt the user for their name
Console.Write("Enter your name: ");
string? userName = Console.ReadLine();
// Validate input (handle null/empty cases)
if (string.IsNullOrWhiteSpace(userName))
{
userName = "Guest";
}
// Greet the user
Console.WriteLine($"Hello, {userName}! Welcome to your first C# project.");
// Add a simple calculation example
int a = 5;
int b = 3;
int sum = a + b;
Console.WriteLine($"Fun fact: {a} + {b} = {sum}");
Building and Running the Project
Now, let’s build and run the updated code.
Using the CLI
-
Build the project: Compiles the code into an executable.
dotnet buildThis creates the
bin/Debug/net8.0folder with the executable (e.g.,CSharpFirstProject.exeon Windows). -
Run the project: Executes the app directly (builds it first if needed).
dotnet runOutput:
Enter your name: Alice Hello, Alice! Welcome to your first C# project. Fun fact: 5 + 3 = 8
Using the IDE
- Run in Visual Studio: Click the green “Start” button (or press
F5). The output will appear in the “Console” window. - Run in VS Code: Open the command palette (
Ctrl+Shift+P), search for “C#: Run and Debug”, and select it.
Debugging Basics
Debugging helps identify and fix errors in your code. Let’s use the IDE’s debugger to inspect variables.
Setting Breakpoints
In Visual Studio or VS Code, click the gutter (left margin) next to a line of code to set a breakpoint (a red dot appears). For example, set a breakpoint on:
string? userName = Console.ReadLine();
Inspecting Variables and Stepping Through Code
- Start Debugging: Press
F5(Visual Studio) or use the “Run and Debug” option (VS Code). - When the breakpoint is hit: The app pauses, and you’ll see a yellow arrow indicating the current line.
- Inspect Variables: Hover over
userNameto see its value (initiallynull). - Step Through Code: Use debugging controls to:
- Step Over (
F10): Execute the current line and move to the next. - Step Into (
F11): Dive into method calls (useful for libraries). - Continue (
F5): Resume execution until the next breakpoint.
- Step Over (
Try entering a name and stepping through the code to watch userName update!
Adding Dependencies with NuGet
NuGet is .NET’s package manager, allowing you to add libraries (e.g., JSON parsers, HTTP clients) to your project. Let’s add a popular package: Newtonsoft.Json (for JSON serialization).
Installing a NuGet Package
Using the CLI:
dotnet add package Newtonsoft.Json
Using Visual Studio:
- Right-click the project in Solution Explorer → Manage NuGet Packages.
- Search for
Newtonsoft.Json→ Select the package → Click Install.
Using the Package in Code
Update Program.cs to serialize an object to JSON:
using Newtonsoft.Json; // Add this at the top (NuGet package namespace)
// Define a simple class
public class Person
{
public string Name { get; set; } = string.Empty;
public int Age { get; set; }
}
// Create an object
var person = new Person { Name = "Bob", Age = 30 };
// Serialize to JSON
string json = JsonConvert.SerializeObject(person, Formatting.Indented);
// Print the JSON
Console.WriteLine("Person JSON:");
Console.WriteLine(json);
Run the project with dotnet run. Output:
Person JSON:
{
"Name": "Bob",
"Age": 30
}
Advanced Topics (Optional)
Testing with xUnit
To ensure your code works as expected, add unit tests. Create a test project:
-
In the CLI, run:
dotnet new xunit -n CSharpFirstProject.Tests cd CSharpFirstProject.Tests dotnet add reference ../CSharpFirstProject # Reference the main project -
Write a test in
UnitTest1.cs:using Xunit; using CSharpFirstProject; // Reference the main project public class UnitTest1 { [Fact] public void Person_Should_Serialize_To_Json() { var person = new Person { Name = "Test", Age = 25 }; var json = JsonConvert.SerializeObject(person); Assert.Contains("Test", json); } } -
Run tests:
dotnet test
Publishing Your Application
To share your app, publish it as a standalone executable:
dotnet publish -c Release -r win-x64 # Windows
dotnet publish -c Release -r osx-x64 # macOS
dotnet publish -c Release -r linux-x64 # Linux
The output will be in bin/Release/net8.0/<runtime>/publish/.
Conclusion
Congratulations! You’ve created a C# project from scratch, written code, added dependencies, and explored debugging and testing. This tutorial covered the basics, but C# and .NET offer endless possibilities—from desktop apps with Windows Forms/WPF to web apps with ASP.NET Core or games with Unity.
Continue learning by exploring:
- C# Documentation
- .NET Tutorials
- Advanced topics like async/await, LINQ, or dependency injection.