DEV Community

Cover image for Basic Console Apps C#
Saoud
Saoud

Posted on

Basic Console Apps C#

Compiling and Executing Programs Terminology


  • Entry Point: Code (usually a method) that's automatically run when a program is launched. In C#, this method is called Main().

Overview & Examples


Setup

Basic boilerplate setup for every C# program:

SomeFileName.csproj

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
    </PropertyGroup>

</Project>
Enter fullscreen mode Exit fullscreen mode

SomeFileName.cs

using System;

class Program
{
  static void Main()
  {
    // program code goes here
  }
}
Enter fullscreen mode Exit fullscreen mode

Running Programs

  • We run a program with the following two steps:
    • Compiling: In the project directory, run > dotnet buildFileName.cs should be the name of the file containing program code. This creates an .exe file.
    • Executing: After compiling, run the following to launch the .dll file: > dotnet run.

General Guidelines

  • Files with .cs extensions contain code written by the developer.
  • Files with .csproj extensions contain project configuration data.

AOT Versus JIT Compiling Overview


  • In modern programming languages, source code must be translated into machine code before computers can understand it. Some languages and platforms do this automatically, but others like C# must be explicitly compiled.

Terminology


  • Compiling: Translating one type of code into another type. Generally this refers to translating a more human-readable type of code into a more complex type of code meant only for computers.
  • Just in Time: When code is compiled as a user interacts with it, as is the case with JavaScript.
  • Ahead of Time: When code is compiled ahead of time, as is the case with C#.

Sample .csproj code:

DoubleIt.csproj

<Project Sdk="Microsoft.NET.Sdk">

    <PropertyGroup>
        <OutputType>Exe</OutputType>
        <TargetFramework>net5.0</TargetFramework>
    </PropertyGroup>

</Project>
Enter fullscreen mode Exit fullscreen mode
  • Build a C# program with the following command: dotnet build.
  • Run a C# program with the following command: dotnet run.
  • The Console.WriteLine() method prints a string to the console.
  • The Console.ReadLine() method is used to retrieve input the user has typed into the command line.

Dotnet Watcher Terminology

Watcher: Monitors files so we don't need to constantly type dotnet run. Here's how we add a watcher:

dotnet watch run
Enter fullscreen mode Exit fullscreen mode

We can also do this with the build command:

dotnet watch build
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)