0
0
C Sharp (C#)programming~5 mins

Project structure and csproj file in C Sharp (C#)

Choose your learning style9 modes available
Introduction

A project structure helps organize your code and files neatly. The .csproj file tells the computer how to build your C# project.

When starting a new C# application to keep files organized.
When adding libraries or resources to your project.
When you want to control how your project is built and run.
When sharing your project with others so they can build it easily.
Syntax
C Sharp (C#)
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
  </ItemGroup>
</Project>

The <Project> tag defines the project and its SDK.

<PropertyGroup> sets project properties like output type and target framework.

Examples
A simple project file for a console app targeting .NET 7.
C Sharp (C#)
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net7.0</TargetFramework>
  </PropertyGroup>
</Project>
This project file is for a class library instead of an executable.
C Sharp (C#)
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <OutputType>Library</OutputType>
    <TargetFramework>net7.0</TargetFramework>
  </PropertyGroup>
</Project>
Adding a package reference to include an external library.
C Sharp (C#)
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>net7.0</TargetFramework>
  </PropertyGroup>
  <ItemGroup>
    <PackageReference Include="Serilog" Version="2.10.0" />
  </ItemGroup>
</Project>
Sample Program

This simple program prints "Hello, world!" to the screen. It would be part of a project with a .csproj file defining it as a console app.

C Sharp (C#)
using System;

namespace HelloWorldApp
{
    class Program
    {
        static void Main()
        {
            Console.WriteLine("Hello, world!");
        }
    }
}
OutputSuccess
Important Notes

The .csproj file is XML, so it must be well-formed with matching tags.

You can edit the .csproj file with any text editor or inside Visual Studio.

Changing the TargetFramework lets you use different versions of .NET.

Summary

Project structure keeps your code and files organized.

The .csproj file controls how your C# project is built.

You can add references and set properties inside the .csproj file.