Language: EN

compilar-c-desde-consola-sin-visual-studio

Compile C# from the console, without Visual Studio

Technology .NET is one of the best advances in task automation available to programmers. Imagine a small program that retrieves data from a drawing made with a design program, performs a series of calculations, opens an Excel sheet to make some graphs, creates a report in a Word file, prints it to PDF, saves it in its folder, and finally makes a record in a database. Well, all this is possible, thanks to the .NET model and technology.

Despite its great features, other languages, such as Bash, Python, or Java, are the ones that are famous for being suitable for creating small scripts for task automation. In comparison, the general opinion about .NET is that it requires a sophisticated and heavy IDE like Visual Studio for its programming. Nothing could be further from the truth. While having an IDE simplifies the work, the truth is that any Windows system capable of running .NET has the necessary tools to compile programs natively.

In this post, we will see how to create a small .NET application using a simple text editor, and compile C# from the console without the need for any additional programs.

Our Hello World in C#

First, we open an empty file with any text editor, and copy the following code

{
  public static void Main()
  {
    System.Console.WriteLine("Hello World");
  }
}

We save the file as helloWorld.cs in any location, for example on the desktop.

Compile and run the application

It is necessary to find out what the latest version of the compiler installed on our computer is. To do this, we look in C:\Windows\Microsoft.NET and find the most current version available. In our case, it is C:\Windows\Microsoft.NET\Framework64\v4.0.30319\

Now we open a command prompt, by running (Windows key + R) and typing CMD, and then pressing Enter. We navigate to the folder where we saved helloWorld.cs and compile using the following command

C:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe helloWorld.cs

This creates an executable with the same name as the class and the .exe extension. To run it, we simply write

helloWorld.exe

We will see that our program obediently displays “Hello World”, just as we expected.

Add compiler to PATH

Finally, if we want to avoid writing the full path to the compiler, we can add the path to the PATH system variable. To do this, we open system properties, inside the control panel. We select environment variables.

propiedades-sistema

We look for the PATH system variable and click on edit.

variables

Finally, we add the address to the end of the variable value, separated by a semicolon.

variable-sistema

Done! Now we can compile any our class (or any other C# class) by simply writing.

csc helloWorld.cs

Did you find this information useful? Do you prefer another language over C# and .NET? Do you have any questions? If you want to give your opinion or suggestions, feel free to leave a comment.