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

Career Advice

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 part 3 of our light introduction to the C# programming language. This series is written for absolute beginners, so please check out parts 1 and 2 before proceeding. They will teach you the fundamentals of C#, variables, a few operations you can do with variables, and how to output basic strings of text incorporating those variables. Once you’ve done that (and understood how they work), in this installment we will look at conditional statements and inputs.

CONDITIONAL STATEMENTS

Before we get started, let’s check out the program we ended with in the previous lesson.

using System;
public class MyMathProgram
{
        static public void Main ()
        {
               int a = 5; 
               int b = 10;
               int c;

               c = a + b;

               Console.WriteLine ( "Hello, world! We just added " + a + "and " + b + "to get " + c );
        }
}

To make things a little easier, note that I renamed the class containing our program to “MyMathProgram.” (But you can call yours whatever you’d like, generally speaking. The same goes for the name of your .cs file containing your code.) Remember also that lines of code can spill over into the next line. Compilers are forgiving with the use of whitespace. What they are really interested in are those semicolons to know where to stop reading and move onto the next thing.

You’ve learned so far that you can add, subtract, multiply, and divide variables. You can also compare them using the following symbols (among others):

  • Less than: <
  • Less than or equal to: <=
  • Greater than: >
  • Greater than or equal to: >=
  • Equal to: ==

To put these new operators to work, we can use what’s called an “if statement,” which is just like it sounds: if something meets this condition, then do this. Let’s check it out in code:

using System;
public class MyMathProgram
{
        static public void Main ()
        {
               int a = 5; 
               int b = 10;

               if ( a > b )
               {
                      Console.WriteLine ( a );
               }

               Console.WriteLine ( "If you did this correctly, the value of a won’t print." );
        }
}

There are a couple of things worth noting here. The first is how we nest blocks of code. That just makes things easier. You could really compress things down in terms of the number of lines of code and the space between things. But starting out, it’s easiest to go for clarity over concision. (Others may disagree.)

Right away, check out the syntax of an if statement:

if ( a > b )

The parentheses contain the conditions that we are feeding to if: namely, is a greater than b. Directly beneath that line, you see an additional set of curly braces { and } in our program. The compiler will do everything inside of if’s curly braces, provided that, in this case, a > b.

Obviously, in our example code, a is not greater than b, which means your program will output the following line:

If you did this correctly, the value of a won’t print.

Note that the conditional if ( a > b ) only applies to what’s inside its block of code. (The code in the curly braces.) The compiler will continue onward to the end of the main() code, top to bottom. There was no condition attached to the final line, Console.WriteLine ( “If you did this correctly, the value of a won’t print.” ); Therefore, it printed.

(It’s a good idea to start thinking in terms of blocks of code, because the concept is never going away.)

If you understand the method and action or an if statement, let’s build on it by adding an else condition.

using System;
public class MyMathProgram
{
        static public void Main ()
        {
                int a = 5; 
                int b = 10;

                if ( a > b )
                {
                        Console.WriteLine ( a );
                }
                else
                {
                        Console.WriteLine ( b );
                }
               
                Console.WriteLine ( "If you did this correctly, you see the value of b." );
        }
}

Hopefully—and especially if you’ve been tinkering around with the code over the course of this series—you are beginning to pick up the basic syntax of C# in the same way you might start picking up phrases of French if you spend time in Paris. In this case, what you are reading basically (or: algorithmically) says: If something is true, then do this; otherwise do this.   

Don’t be afraid of code!

The use of else in our example means that only one of the two Console.WriteLine() methods in the if/else blocks will execute. Either the program will print the value of a, or it will print the value of b. Compile the program and run it. If you typed everything correctly, it will obviously print 10 to the screen, as 5 is not greater than 10.

USER INPUT

By now you are probably getting antsy for something a little more sophisticated in your code. Be patient. You need to walk before you can run. Right now you’re learning syntax. In the next entry in the series, we will take everything we’ve learned and build an actual program that does something useful.

The last thing we will learn today is basic string input. We will write code to let the user type in a word, which we will then use in our program.

  • The code for writing a string of text to the console is Console.WriteLine();
  • The code for reading a string of text from the console is Console.ReadLine();

Check out how readable Console.WriteLine and ReadLine are. What does Console.ReadLine do? It reads a line from the console! This is something you are always striving for when writing software: readability. Console.ReadLine() is also our first dip into something called return values. The method Console.ReadLine() is going to work its mojo, and then toss back the value that the user enters. In this case, it always tosses back (or formally: “returns”) a string value. In order to use the value, we need to declare a string variable (the same way we declare an integer!) and use that variable to catch the return value. Let’s see it in code:

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


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


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

In this code, the string variable name receives a value returned by Console.ReadLine—a value that was entered by the user! To make things a little neater for the user, rather than use Console.WriteLine for the initial request for a name, we can use Console.Write(), which will allow us to prompt the user and accept his or her input on the same line.

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 );
        }
}

Console.ReadLine() is a method with a string return value. Methods can also receive values, and you’ve already done that! Console.Write( “What is your name?” ) is receiving the string “What is your name?” In the next and final entry in this series, we will code a useful program, and will actually write a method of our own that receives a value and returns a different value.

Before we go, though, one final point: You might be wondering where these Console methods are coming from, and how you could possibly know their names and how to use them? First: They come from the very top line of every program we’ve written: using System;

System is a namespace (or: a big, organized group of things) containing hundreds of useful classes and clever methods pre-written for you. When you write Console.Write(), you’re not writing the hundreds of lines of code necessary to actually print words on a screen with proper formatting. Microsoft did all of that work for you, and you are simply using the method interface to take advantage of it. How does Console.Write work? Magic. Don’t even worry about it. Just be grateful that such tools are ready and waiting for you to find and use.

And you can find them at Microsoft’s .NET framework site here. Check it out. In the left pane, under System, scroll down to Console and click it. Then click its methods. You’ll notice a few familiar friends. Click ReadLine, and you’ll see all the details you could ever want to know about it. Between now and the next entry in this series, explore those different methods and see if you can use a few we haven’t yet discussed. Moreover, try mixing and matching the code that you’ve learned so far in parts 1 and 2. See if you can write a conditional statements that involve reading text entered by a user. See what you can break, and then see if you can fix it. It’s the only way to learn this stuff. See you in part 4!

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