0
0
CsharpHow-ToBeginner · 4 min read

How to Run C# Program from Command Line Quickly

To run a C# program from the command line, first compile it using dotnet build or csc compiler, then execute the generated file with dotnet run or by running the executable directly. Using dotnet run is the simplest way for .NET Core projects.
📐

Syntax

Here are the basic commands to compile and run a C# program from the command line:

  • dotnet run: Compiles and runs a .NET Core project in one step.
  • dotnet build: Compiles the project into an executable.
  • csc Program.cs: Compiles a single C# file using the C# compiler (for .NET Framework or .NET SDK).
  • ./Program.exe or Program.exe: Runs the compiled executable on Windows.
bash
dotnet run

// or

dotnet build

dotnet ./bin/Debug/net6.0/YourApp.dll

// or

csc Program.cs
Program.exe
💻

Example

This example shows how to create a simple C# program, compile it using dotnet run, and see the output.

csharp
using System;

class Program
{
    static void Main()
    {
        Console.WriteLine("Hello from C# command line!");
    }
}
Output
Hello from C# command line!
⚠️

Common Pitfalls

Common mistakes when running C# programs from the command line include:

  • Trying to run .cs files directly without compiling.
  • Not having the .NET SDK or runtime installed.
  • Running dotnet run outside a project folder with a .csproj file.
  • Confusing dotnet run (for .NET Core/5/6+) with csc (classic compiler).
bash
/* Wrong way: */
// Trying to run source file directly
// > Program.cs

/* Right way: */
// Compile then run
// > csc Program.cs
// > Program.exe
📊

Quick Reference

CommandDescription
dotnet runBuilds and runs a .NET Core project in one step
dotnet buildCompiles the project into an executable or DLL
csc Program.csCompiles a single C# file into an executable
Program.exe or dotnet YourApp.dllRuns the compiled executable or DLL

Key Takeaways

Use dotnet run inside a project folder to compile and run quickly.
For single files, use csc Program.cs to compile, then run the executable.
You cannot run C# source files directly without compiling first.
Make sure the .NET SDK is installed and your command line is in the correct folder.
Understand the difference between dotnet run (project-based) and csc (file-based compiler).