codelessgenie guide

Creating a C# Project from Scratch: A Hands-On Tutorial

C# (pronounced "C sharp") is a versatile, object-oriented programming language developed by Microsoft. It’s widely used for building desktop applications, web services, mobile apps (via Xamarin), games (with Unity), and more, thanks to its integration with the .NET ecosystem. Whether you’re a beginner taking your first steps in programming or an experienced developer exploring C#, creating a project from scratch is the best way to get hands-on with the language. In this tutorial, we’ll guide you through every step of building a C# project from the ground up. We’ll cover setting up your development environment, creating a project (using both the command line and an IDE), understanding the project structure, writing code, debugging, adding dependencies, and even touch on advanced topics like testing and publishing. By the end, you’ll have a functional C# application and the confidence to build more complex projects.

Table of Contents

  1. Prerequisites
  2. Setting Up Your Development Environment
  3. Creating Your First C# Project
  4. Understanding the Project Structure
  5. Writing Your First C# Code
  6. Building and Running the Project
  7. Debugging Basics
  8. Adding Dependencies with NuGet
  9. Advanced Topics (Optional)
  10. Conclusion
  11. 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:
  • 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

  1. Download the SDK:
    Visit the .NET 8 download page and select the installer for your OS (Windows, macOS, or Linux).
  2. Run the Installer:
    Follow the on-screen prompts. For Windows, ensure “Add to PATH” is checked.
  3. Verify Installation:
    Open a terminal/command prompt and run:
    dotnet --version  
    You should see output like 8.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:

  1. Open a Terminal:
    On Windows, use Command Prompt or PowerShell; on macOS/Linux, use Terminal.

  2. 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  
  3. Create a Console App:
    Run the following command to generate a new console application project:

    dotnet new console  

    The dotnet new command creates a project from a template (console is the template name for console apps).

  4. Verify the Project:
    You’ll see output confirming the project was created. List the files in the directory:

    dir  # Windows  
    ls   # macOS/Linux  

    You 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:

  1. Open Visual Studio and click “Create a new project”.

  2. Select a Template:
    Search for “Console App (.NET)” and select it. Click “Next”.

  3. Configure Project:

    • Project name: Enter CSharpFirstProject.
    • Location: Choose a folder to save the project.
    • Framework: Select .NET 8.0 (LTS).
      Click “Create”.

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.Sdk for console apps).
  • OutputType: Exe means the project builds an executable (.exe on 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 Main method 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 build  

    This creates the bin/Debug/net8.0 folder with the executable (e.g., CSharpFirstProject.exe on Windows).

  • Run the project: Executes the app directly (builds it first if needed).

    dotnet run  

    Output:

    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

  1. Start Debugging: Press F5 (Visual Studio) or use the “Run and Debug” option (VS Code).
  2. When the breakpoint is hit: The app pauses, and you’ll see a yellow arrow indicating the current line.
  3. Inspect Variables: Hover over userName to see its value (initially null).
  4. 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.

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:

  1. Right-click the project in Solution ExplorerManage NuGet Packages.
  2. 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:

  1. In the CLI, run:

    dotnet new xunit -n CSharpFirstProject.Tests  
    cd CSharpFirstProject.Tests  
    dotnet add reference ../CSharpFirstProject  # Reference the main project  
  2. 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);  
        }  
    }  
  3. 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:

References