C# 001: Hello World

This is the first in a series of articles describing how to program in C#. We'll start from the very beginning and provide the building blocks for you to create more elaborate applications.

To start out, you'll need some tools. C# is a compiled language. That is, the source code is converted to a binary executible by a tool called a compiler. You can get a free compiler by downloading the Community edition of Microsoft Visual Studio.

Most of the tutorial will use Visual Studio. However, since this is the first post, we'll create a program from the command line. After installing Visual Studio, open the Developer Command Prompt. This will open a command prompt that has all the developer tools (compilers) available.

As per programming tradition, we'll start with a Hello World application. Hello World is a simple command line app that prints "Hello World" to the console.

To start out, create a new text file named HelloWorld.cs and open it in Notepad.exe (or your favorite text editor.) Paste the following text into the file and save it.

class Program() {
    static void Main() {
        System.Console.WriteLine("Hello SteemIt");
    }
}

C# is designed to be (mostly) readable. So even if you've never seen C# before, you can probably guess what the application will do. It will print the text, "Hello SteemIt" to the console.

We'll dive deeper into the syntax in later posts, but for now, you might observer a few things. First the System.Console.WriteLine line ends with a semicolon (;). In C# all statements must end in a semicolon. Second, the text "Hello SteemIt" is surrounded by double-quotes. In C# strings are always surrounded by double-quotes.

After saving the file, return the to command prompt and type the following.

csc.exe -t:exe HelloWorld.cs

csc.exe is the C# compiler. When using Visual Studio, you don't interact directly with the compiler like this. Visual Studio hides all the details from you to make it easier. But since this is the first post, you should step through the mechanics of what's happening behind the scenes.

The -t switch tells the compiler what type of binary to produce. In this case, -t:exe says to create an executable.

The last parameter is the name of the C# file to compile. HelloWorld.cs is the file you saved earlier.

After running the command, you'll notice a new file has been created, HelloWorld.exe. If you run the command, you'll see the text "Hello SteemIt" printed to the console.

Congratulations, you just created your first application in C#!

You should try modifying the string in the HelloWorld.cs file, compiling and running the app. Try replacing "Hello SteemIt" with "This is easy!".

HelloWorld.png

H2
H3
H4
3 columns
2 columns
1 column
Join the conversation now