C# for the Impatient, Lesson 1 – The Basics

To be able to follow this tutorial, I assume that you have a working Visual Studio environment (I’m using VS2013). I’m pretty sure there are other ways to create C# programs (mono for example) but for beginners VS does a lot of magic that saves time. Maybe later as I understand the basics, I’ll investigate other options for creating and building C# programs. I also assume that you already know how to program and are just searching for a fast way to get started on C# (just like what I am doing/did), so I’ll be skipping many details here. All code examples in this tutorial are located at github, so you don’t have to copy and paste all the time from the browser.

We’ll start by creating a simple console application in which we will learn the basics of the language. This is done by selecting “File–>New–>Project”. Select “Console Application” under The “Templates–>Visual C#–>Windows” tree on the left. You have three things to decide: the name of the project, the name of the solution, and where they are located. A few words on solutions and projects: A solution is a logical grouping of projects. A project MUST be contained inside a solution. A solution may contain more than one project, and also elements that are not part of a specific project, like build files, or configuration files. A project is usually a single application component (.exe, .dll, service role, etc.). I created a solution called “learning-csharp”, and my first project is called “lesson1″. VS works it’s magic and opens a new file “Program.cs” that I can start editing. So let’s do the typical example and print “hello world” to the console:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");
        }
    }
}

Now hit F5 to run the program. You will see a console that opens and closes. What’s wrong here? nothing – VS opened a console, executed the app and when the app finished, closed the console. But we want to see that the program really worked! so let’s add something that leaves the console open. This is easy – ask the user for input:

using System;

namespace lesson1
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("Hello World");
      Console.ReadLine();
    }
  }
}

Now if you hit F5, the console will print “Hello World” and will stay on top, waiting for the user to enter something and hit enter. So go ahead and hit enter. This will let the program finish and close the console window.

Great, we have our first program running. Now let’s do a quick run on the language basics, starting with variables. Variables are declared giving them a type and a name, and optionally an initial value. For example:

int i = 1;
bool b = true;
string s = "hello";

When you type this in VS, you probably saw something interesting: auto-complete proposes both string and String, or int and IntXX where XX can be 16, 32, and 64. From the “simple programmer” POV, they are the same (Int16 is short, Int32 is int, etc.). Under the hood, we have both primitive types (int, bool, string) and classes (Int32, String). Bear with me here, we’ll get to classes later), with a direct matching between a primitive type and an a class. The primitive type is probably stored in a smaller memory space and when used as an object it is Boxed, and when an object is set into a primitive type it is Unboxed. So use the ones you like, just know that using only class types may reduce your performance because of Boxing/unboxing.

So let’s extend our function to write some variables and their values (changes only in the main function). I also added a new trick that shows how to print multiple variables to the console:

static void Main(string[] args)
{
  Console.WriteLine("Hello World");
  int a = 1;
  bool b = true;
  String c = "Something";
  var d = 34.5;
  Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
  Console.ReadLine();
}

Oh, I missed another cool (IMHO) feature of C# – the var declaration. I won’t get into details here (mainly because I don’t know them), but the idea is that if the compiler can understand what is the type of the value of a variable, then you can declare it as var. This comes really handy when you have long type names – which are a good practice. To finish this basic section, let’s define a couple of arrays. The array definition is similar to C/C++/Java. As a Java programmer, I tried using int array[] but it doesn’t work. So don’t try it.

int[] arr1 = {1,3};
int[] arr2 = new int[5]; 

Now for some control structures. We have the usual suspects here: for, while, and do-while.

for (int i = 0; i < 5; i++)
{
    Console.WriteLine("i is {0}.", i);
}

int j = 5;
while (j >= 0)
{
    Console.WriteLine("j is {0}.", j);
    j--;
}

int k = 5;
do
{
    Console.WriteLine("k is {0}.", k);
    k--;
} while (k >= 0);

And the unusual one: foreach.

int[] l = { 1, 2, 3, 4, 5 };
foreach (var item in l)
{
    Console.WriteLine("item is {0}.", item);
}

So putting everything together, here’s the program we have:

using System;

namespace lesson1
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World");

            // simple variables;
            int a = 1;
            bool b = true;
            String c = "Something";
            var d = 34.5;
            Console.WriteLine("a = {0} is an integer, b = {1} is a boolean, c = {2} is a string, d = {3} is a var", a, b, c, d);
            Console.ReadLine();

            // Arrays
            int[] arr1 = {1,3};
            int[] arr2 = new int[5];

            for (int i = 0; i < 5; i++)
            {
                Console.WriteLine("i is {0}.", i);
            }
            Console.ReadLine();

            int j = 5;
            while (j >= 0)
            {
                Console.WriteLine("j is {0}.", j);
                j--;
            }
            Console.ReadLine();

            int k = 5;
            do
            {
                Console.WriteLine("k is {0}.", k);
                k--;
            } while (k >= 0);
            Console.ReadLine();

            int[] l = { 1, 2, 3, 4, 5 };
            foreach (var item in l)
            {
                Console.WriteLine("item is {0}.", item);
            }
            Console.ReadLine();

        }
    }
}

I think this is enough for a first lesson. Before we finish, let’s talk a bit about conventions. As an experienced (and pedantic) programmer, I really like to follow language conventions, both in the formatting and in the naming of elements. This is because conventions makes it easier to read code by reducing how much the brain has to process, because it recognizes the convention as a pattern in the code (I just made up that explanation, but I’m sure I can prove it anecdotally). So these are the basics (based on this and this articles):

  • Names use camelCase. Variables with initial lowercase, classes with initial uppercase.
  • Every statement is in one line, including opening and closing braces (this REALLY bothers me).
  • 4 spaces indentation
  • Namespaces should follow the [Company].([Product]|[Technology]).[Feature].[Subnamespace] format.

Hope you enjoyed the tutorial. More will be coming (hopefully) soon.