Part 4: Want to Write Code? How to Program in C#

Career Advice

(Photo Credit: Bruce Mars from Pexels)

There are over ten thousand jobs listed in the Clearance Jobs 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 the fourth and final part of our light introduction to the C# programming language. This series is written for absolute beginners. Please check out parts 1, 2, and 3 before proceeding. There you will learn the basics of C#, to include the basic structure of a program, variables, conditional statements, and basic user input. In this entry, we will learn to write our own methods, and will build a program that actually does something useful.

A METHOD TO THIS MADNESS

First, let’s look at the final program that we wrote in part 3.

using System;
public class MyNameProgram
{
        static public void Main ()
        {
                string name;

                Console.Write ( "What is your name?" );
                name = Console.ReadLine();

                Console.WriteLine( "Your name is " + name );
        }
}

At this point, should be very familiar with creating your own files, compiling them, and running them. (If you are having difficulty, please refer back to Part 1.) In the above code, you’ll see that we declare a string called name, prompt the user to enter a name, and then write the name to the screen. Notice that Console.ReadLine returns a value—in this case, a value of the string type. The variable name receives the value, and we are able to use it in the final line of code.

Before pressing forward, I’d like to write something in pseudocode—this won’t be formal C#. It’s just a way of describing how something is working. First, a little thought experiment: In regular grade school math, 2 + 2 = 4 is the same as 4 = 2 + 2. When you are thinking about return values, the second example, 4 = 2 + 2, is the general idea. So let’s write that out in pseudocode:  

totalNumber =  AddNumbers( firstNumber, secondNumber )

Logically, you should be able to look at that pseudocode and intuit what’s going on. The variables firstNumber and secondNumber are passed to the (fictional) method add, and after add does its magic, it spits a number out that is received by totalNumber.

So let’s imagine what it must look like on the inside of the AddNumbers. First: it’s going to be a block of code, so we know there will be some curly braces involved. We know also that Main is a method, so it’ll probably use the same general format. So first, let’s copy Main.

static public void Main ()
{
       string name;
 
       Console.Write ( "What is your name?" );
       name = Console.ReadLine();

       Console.WriteLine( "Your name is " + name );
}

 

One thing to keep in mind: What happens in a method, stays in a method (unless otherwise directed). So when we create a method that exists outside of Main, we cannot access Main’s code or variables. Likewise, Main cannot access the variables of our AddNumbers method. They talk to each other only through interfaces. If you like analogies, think of a method as a household appliance. Say, a toaster. When you make breakfast in the morning, you don’t take out a screwdriver, wires, soldering iron, and car battery to make toast. The toaster exists as its own entity. We give it something—bread, and it returns something to us—toast. Likewise, your toaster doesn’t go to your pantry, pull out fresh slices of bread, and toast it for you. The toaster has its world, and you have your world.

Methods work exactly the same way. So let’s change up Main to fit the general description of what we want to do. On the first line, you see the words static public void. The type void just means that the method will not be returning a value. For the purposes of this introductory series, just accept that static and public are required. (They aren’t, and there are all sorts of other ways we can do this, but that is outside the scope of this series.) But one thing we do know: our method is returning something. Specifically, we know that AddNumbers will be returning an integer. So let’s replace void with int. The first line, so far, should look like this:

static public int AddNumbers ()

So far, so good. We also know that AddNumbers will be receiving two integers. Remember: AddNumbers is its own world. So we can’t just write int AddNumbers ( a, b ) because a and b don’t exist, and the compiler doesn’t know what variable types they are. So we will need to declare them.

static public int AddNumbers( int a, int b )

Just looking at that line, we know what our method will return (an integer) and what it is receiving (two integers). You’ll notice that I called them a and b. I could have called them anything I wanted. Duck and Cow. Foo and Bar. Even firstNumber and secondNumber. Because AddNumbers is its own entity, we don’t have to worry about anything going on in Main. We are painting on a clean canvas: a and b do the job perfectly, and for clarity, that is what I used.

Just like Main, the block of code will be delineated with curly braces.

static public int AddNumbers( int a, int b )
{

}

And what do we want to do inside of AddNumbers? We want to add a and b, and return the sum. The sum, of course, is an integer.

static public int AddNumbers( int a, int b )
{
        int c;

        c = a + b;
        return c;
}

The code to return something is… return. (See, programming isn’t that difficult!) So now you have the basic idea behind a method. And going forward, you could take this code to any number of programs you write in the future, and it world work. Why? Because it is totally self contained.

So where does our new method fit in the larger program? We will place it inside the same class as Main.

using System;
public class MyNameProgram
{
        static public void Main ()
        {
                string name;

                Console.Write ( "What is your name? " );
                name = Console.ReadLine();

                Console.WriteLine( "Your name is " + name );
        }

        static public int AddNumbers( int a, int b )
        {
                int c;

                c = a + b;
                return c;
        }
}

Go ahead and create a new cs file, paste the above code, and run the program. What do you see? No difference between this one and the program we wrote previously! Why? Because we never call AddNumbers in the Main method. Remember: the program is only going to run the code in Main. And in the above example, we never actually mention the method in Main.

(In the real world, Main might only call one or two methods, but those methods will call methods of their own, which call methods of their own, crossing classes and namespaces. The whole thing will explode outward like a star going supernova.)

So let’s actually try out our new method by calling it.

using System;
public class MyNameProgram
{
        static public void Main ()
        {
                string name;
                int total; 

                Console.Write ( "What is your name? " );
                name = Console.ReadLine();

                total = AddNumbers ( 2, 3 );

                Console.WriteLine( "Your name is " + name + " and your sum is " + total );
        }

        static public int AddNumbers( int a, int b )
        {
                int c;

                c = a + b;
                return c;
        }
}

Compile your code and try it out. Here was my output:

What is your name? David
Your name is David and your sum is 5

TEMPERATURES RISING

So far so good. Now we are going to write a program to convert temperatures in Fahrenheit to Celsius. While this won’t change your life, at least you can say that you programmed something useful.

First, recall that the Console.ReadLine method always returns a string type. And as we have discussed in previous entries in this series, you can’t add strings together; it would be nonsensical, like adding the words “duck” + “goat.” It does not compute to the human mind, and won’t compute for the compiler, either.

So what do we do? There exists in C# a method for converting a string to an integer. (As we discussed in the last entry, there is no way you could possibly have known that. You would have had to search the Microsoft C# reference, but honestly, the easiest way would have been to search Google. Something like: How do I convert a string to an integer in C#?)

The method for making that conversion is int Convert.ToInt32( string );

So our plan of attack: Use Console.ReadLine just like normal—the same way it would read a name, it will read a number. Remember: just as Excel cannot add text cells together, a string is just a piece of text that happens to be a number. We will have to convert it to a number before we can use it in arithmetic. We will then pass the string the user entered to Convert.ToInt32(), and that method will return an integer that we have to receive and use.

Let’s look at that code:

using System;
public class MyNameProgram
{
        static public void Main ()
        {
                string numberString;
                int fahrenheit;

                Console.Write ( "Enter a temperature in Fahrenheit: " );
                numberString = Console.ReadLine();

                fahrenheit = Convert.ToInt32( numberString );

                Console.WriteLine( "The number you entered is " + fahrenheit );
        }
}

We created a generic numberString variable to accept the user input, and an integer, fahrenheit, to receive the integer value from the converted string.

We passed numberString to the method we just learned, and it spat back out an integer that we assigned to fahrenheit. (As usual, we could have called that variable anything, but since we are about to write a temperature conversion, I thought that easiest.)

Now that we have the conversion out of the way, everything else is a breeze. Instead of adding two numbers, we will do math that’s slightly more elaborate. To convert Fahrenheit to Celsius, you take Fahrenheit and subtract 32. Then you multiply the whole thing by 5/9.

The equation written out looks like this: c = (f – 32) * 5 / 9.

(Don’t be freaked out by that. It’s third grade math. Math doesn’t change just because you’re using it in a computer program.)

So now let’s write our conversion method.

static public int ConvertFtoC( int f )
{
        int c;

        c = (f - 32) * 5 / 9;

        return c;
}

You’ll notice exactly the same format as our AddNumbers method. All we did was change the math used. It still accepts an integer. It still returns an integer. (Note that this program is just going to round the temperature to the nearest degree. You could also rewrite the method and main program using doubles to get a more precise conversion. That would be a great way to practice doing a little coding without your hand being held, and you’ll also have to look up how to convert a string to a double value.)

Now all we do is add our method to our code, and call it. The final program should look like this:

using System;
public class MyNameProgram
{
        static public void Main ()
        {
                string numberString;
                int fahrenheit;
                int celsius; 

                Console.Write ( "Enter a temperature in Fahrenheit: " );
                numberString = Console.ReadLine();

                fahrenheit = Convert.ToInt32( numberString );

                celsius = ConvertFtoC ( fahrenheit ); 

                Console.WriteLine( "The temperature in F to the nearest degree C is " + celsius );
        }

        static public int ConvertFtoC( int f )
        {
                int c;

                c = (f - 32) * 5 / 9;

                return c;
        }
}

Here is the output I got when I compiled and ran the program:

Enter a temperature in Fahrenheit: 212
The temperature in F to the nearest degree C is 100

Congratulations! You have just written your first useful program.

NOW WHAT?

Now that you have sampled the waters, it’s time for you to swim. There are hundreds of places online to further your education of C#, and scores of books at the library as well. I learn best from books—any introductory text will do, and if your library doesn’t have one, just request it. I’ve found that librarians are in a constant struggle to have up-to-date computer books, and are always happy to improve their collections.

Another place I’d strongly recommend is Udemy, which allows you not only to sample the courses, but to move at your own pace. I highly recommend the ones taught by Ben Tristem, because you can watch him type the code on the screen and explain what he’s doing as he’s doing it. His course is also great because he teaches you C# by walking you through how to write computer games. It’s a lot of fun, and almost as exciting as converting temperatures. 

And so you are now set. I hope you found this series useful, and if you made it this far, I hope you’ll share it with your friends. If you find any problems in the code, or need help, please share it in the comments or send me an email. And if you keep going, best of luck in your next career!

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