Want to Write Code? How to Program in C#

Career Advice Teen at Computer Gaming

There are over ten thousand jobs listed in the ClearanceJobs database for software developers. If you are looking for a career change, each one of those listings is an opportunity to start over. It might seem like an intimidating leap, but here is the thing: It’s a lot easier to learn a programming language than it is to get a security clearance, which means if you are reading this, you’ve done the hard part already.

There are a number of great resources online for learning any programming language. In this four part series, ClearanceJobs will introduce you to software development. We will discuss the tools you need—all of which are free—and get into basic programming concepts. Once you get the software installed and begin experimenting, you can reach any level of ability you desire. It’s just a matter of putting in the hours.

This is a light introduction to the C# programming language. We’ll use this language because it is modern, easy to learn, and related closely enough to C, C++, and Java that you could hop to any of those languages without too much difficulty. (Once you get into the weeds, those languages are highly distinctive, but we are staying in the shallow end of the pool.) So let’s get started.

PART 1: WHAT IS C#

Good question! C#—pronounced C-sharp—is a flexible, object-oriented programming language generally used for developing software in Microsoft Windows, but available also for Mac and Linux. It is a descendent of the C++ programming language, which is itself descended from C. (Before C there was… B… but C is sort of like the Latin of programming languages. It was a brilliantly designed language that proliferated at universities in the 1970s, and whose paradigms would stand the test of time. All would proceed from there).

As a programmer, you will spend a lot of time writing code. Code is the human-readable version of software. Generally speaking, before the computer can do anything with all the code you’ve written, it must first be “compiled,” or converted into binaries—”machine code”—that a computer can read. In this series, we will use a compiler called Mono. It is free, lightweight, and runs on just about everything.

HELLO, WORLD

So what does C# code look like? Brace yourself: it’s not hard, but there’s an upfront intimidation factor that you just have to power through. Even if you can’t quite understand the concepts presented below, just accept them as the cost of doing business. As we write more complex programs over the course of this series, you’ll come to understand everything you see here, and looking back, wonder how it was ever a mystery.

To make things official, we have to write a “hello, world” program. It’s a developer tradition when first starting out in a new language, and a useful way to ease into a new way of doing things. So let’s jump right in. Here is the structure of a simple C# program. Once compiled and executed, this code will print a single line that reads: hello, world.

using System;

public class MyFirstProgram
{
    static public void Main ()
    {
         Console.WriteLine ("hello, world");
    }
}

If you’ve never written a program before, hold it together: this is a lot easier than it looks. Let’s start where the action happens. Based on what we know about what the program is supposed to do, you can infer that Console.WriteLine (“hello, world”); is the main event. And you are correct! We will break down the line in a minute, but first: check out that semicolon on the end. That is how you end a statement in most C-based programs. The other time a semicolon is used is in the first line: using System; (The other lines are basically used to separate and organize blocks of code based on purpose. We will discuss that in greater detail below. Again, if any of this is overwhelming, just accept what you are seeing and move on. It’ll make sense in time.)

WHAT IS AN OBJECT?

Object-oriented programming languages generally use something called “classes,” which are essentially templates and generally intended for reuse. We will not go deep into classes in this tutorial, but a good way to understand a class is to think of your car.

Let’s say you drive a Ford Focus. What is it? It is a car. What is a car? A type of automobile. Right away, we have three classes to work with: Ford Focus, Car, and Automobile. Each, you will notice, is increasingly abstract.

An automobile is a vehicle with four wheels with some sort of motor. What can it do? It can accelerate and it can brake. A car inherits each of those traits—four wheels, motor, abilities—but is a bit more specific. It also has doors and a trunk of some sort for storing things. A Ford Focus inherits all of this—the four wheels, the motor, the trunk, the abilities—and specifically has four doors and holds five people.

The beauty of classes when you are writing software is that you can reuse a lot of work for future programs. Let’s say you want to build a Ford GT. You don’t have to reinvent the automobile or the car. You need only create a new class that inherits the traits of the automobile and the car. All you have to write is a Ford GT class that has has two doors and two seats.

Ford GT is a subclass of Car, which is a subclass of Automobile.

Ford Focus is a subclass of Car, which is a subclass of Automobile.

Taking things one step further: As you know, automakers don’t build a single car and call it a day. You don’t drive the only Ford Focus on the road. Automakers build lots of cars. Your Ford Focus is an object—a single instance of the class of cars called Ford Focus. Every Ford Focus on the road is such an object.

All of this is the simple case, obviously. But you can think forward and imagine where “Truck” fits in this hierarchy. You wouldn’t have to reinvent the Automobile class—all those details remain the same. But would not be a car. You would create a subclass of Automobile called Truck, giving it the detail of a bed. And from there, you could have subclasses called F-150 or Silverado or what have you.

In small programs, it might seem silly to do all this work for something relatively simple. But in extremely large programs, you might be talking about tens of thousands of lines of code describing things of increasing abstraction.

APPLYING THESE LESSONS TO THE ABOVE CODE

Let’s look again at the “hero” of the program above:

    Console.WriteLine ("hello, world");

Console is a class that that handles the input and output of your software. In this case, we are only concerned with the output. Just like the Ford Focus class we invented “inherited” the accelerate and brake abilities, the Console class has the ability (among many other things) to write a line on the screen. We feed it a parameter—“hello, world” —and it does the work. We don’t even need to know how WriteLine does it! All we need to know is its “interface”: what to feed it—in this case a string of characters surrounded by quotation marks.

You’ve undoubtedly noticed that the above code is nested in the curly braces { and }. The name of the “outer” nesting is: static public void Main ()

Don’t worry too much about “static” and “public.” They relate closely to how certain features of C# work, and they are outside the scope of this article. Just accept that they make the program work, and leave them be.

Void Main (), though, is interesting.

Main () is called a method. A method is a grouping of one or more statements that an object can do. Just about every C-based program has a Main of some sort. No matter if you’ve written a million lines of code, the compiler will always look for Main to set everything in motion. It’s the first domino to fall.

Methods—those grouped lines of code—can accept parameters. Those parameters are called “arguments.” Methods can also spit out a value. In this case “Void” means it doesn’t spit out a value. It tells the computer and the programmer: Don’t expect any output from me!

But what if you saw a method that began like this:

    int addTwoNumbers( int a, int b )

Can you guess: 1. What the method does; 2. What arguments it accepts; and 3. What sort of thing it returns?

Based on its descriptive name, you can safely assume that the method adds two numbers together—that the numbers being added together are integers a and b—and that after the method does the addition, it spits out—it returns—an integer value. Some sort of whole number. (NOTE: You can name your methods, classes, or variables ANYTHING YOU WANT. Good writing practice dictates that you give things names that make your code easily understandable.)     

So bringing all of this together and going back to the Hello World introduction: When the code is run, the computer looks in main and sees that it has been instructed to look in the class called Console for the method WriteLine, and that we—the programmers—have told WriteLine to accept the argument “hello, world”.

All of this is inside the class called MyFirstProgram, which we have created to do this thing for us. (Namely: write the words “hello, world.”) Again, for comparative purposes, had we written a car program, you might have sees something like FordFocus.Accelerate( 75 );

There’s one more thing we need to look at. The top line of the program says:

    using System;

Don’t get too hung up on this. Everything we write will use System. It is a namespace, which is basically just a big group of things. One of those things is the class Console, which contains the method WriteLine. (It is outside the scope of this series of articles.)

So having gone through the entire program, let’s look at it again:

using System;

public class MyFirstProgram
{
    static public void Main ()
    {
         Console.WriteLine ("hello, world");
    }
}

Every single program we write in this series will use the above lines of code. Each lesson, we will add functionality to it: the stuff inside of the curly braces { and }  will change, but everything else will more or less remain the same. Think of this as your core program going forward.

COMPILING THE CODE

As stated above, we will use the Mono compiler to build our program. The program can be found here. Select your platform (Windows, Mac, Linux) and download it and install it like any program. (Windows users have the choice of 32-bit or 64-bit, depending on the version you are running; 64-bit should generally work perfectly.) In each case, I encourage you to avoid the Visual Studio version, and stick with the vanilla Mono package.

Mac users and Linux users have it easiest. Once you install, you should be able to run csc and mono—the two programs we are most concerned with—from any folder. Windows users will have to run the applications from c:\Program Files\Mono. (Windows users are encouraged as well to use this folder as your active working folder. Save your code here. It’ll save time when typing commands.

Step 1 to compiling your code is to first save it in a plain text file. In Windows, this means Notepad. On a Mac, this means TextEdit. (In the case of TextEdit, be sure to make it a plain text file. Copy the above code into your text editor and save the file as hello.cs. (NOT hello.txt. Macs in particular like to append .txt to files. Be sure to remove it. It must be called hello.cs. And don’t forget, Windows users: save hello.cs to c:\Program Files\Mono)

The next step is to go to your Command Prompt or Terminal. In Windows, Mono will create a shortcut in your windows menu called “Open Mono x64 Command Prompt.” Click that. On a Mac, you can call up the Terminal by doing a search in Finder. Make sure you are in the same folder as your hello.cs file, and type:

    csc hello.cs

    Press <enter>.

If you do not receive any error messages, congratulations! You have just compiled your first C# program. If you receive error messages, figure out of the problem is related to the code (it will tell you) or if the problem is because it cannot find hello.cs, in which case you are in the wrong folder. Browse to the correct one and try again.

If you are successful, the code you have written has been translated into machine-readable code. If you search the directory, you will see that a new file has been created: hello.exe.

To run the program, type

    mono hello.exe

    Press <enter>.

Your terminal should read:

    hello, world

Congratulations! You have completed all of the steps of our first lesson.

Note that “Mono” is the “runtime” for hello.exe. Think of it as the machine that runs the widget you just built. In a wider enterprise environment—in that job you’d like one day to get—not everyone will use C#. Someone else might be using Visual Basic, for example. By abstracting things to a runtime rather than a standard, universal executable, programs written in C# or Visual Basic can have the same functionality. The runtime speaks both languages. When you’re dealing with hundreds of developers spread across dozens of locations, this makes life a lot easier for everyone involved.

PREPARING FOR THE NEXT LESSON

The next lesson will assume that you

  1. Have installed Mono.
  2. Know how to create a plain text file with the cs extension. (For example: hello.cs)
  3. Know how to successfully compile a C# program (hello.cs).
  4. Have successfully run the program you have just created.

If you have questions, please post them in the comments and I will check them regularly. Similarly, if you’ve spotted an error here, please let me know here or by email at davidwbrown@gmail.com. (When reporting “errors,” keep in mind that I’ve painted with very wide brushstrokes here. The idea is to get a total novice on his or her feet. The nuances can be learned in time. This isn’t the forum to split hairs and show off your insane C# skills.)

Good luck! See you in a couple of weeks.

David Brown is a regular contributor to ClearanceJobs. He is currently at work on his next book, One Inch From Earth, which tells the story of scientists who study the outer planets of the solar system. He can be found online at http://dwb.io.

More in Career Advice