The Definitive Guide to C# for Software and Video Games

Do you want to build websites, mobile apps, or make awesome games with Unity? Then C# is the programming language for you!

The popular, powerful, and versatile Unity Game Engine utilizes C# as the programming language that powers its Scripting API – allowing you to implement game logic, trigger events, apply physics, respond to user input, check for collisions and so much more! However, C# is also a very popular language for software developers as well due to its high efficiency. Either way, knowing C# can be a big boost for your careers and hobbies alike.

This article seeks to demystify C#, get you started with some of the fundamentals, and give you a path to dive into further learning material. We’re assuming no prior programming experience here, so the information found here is suitable for complete beginners as well as developers coming from other programming languages. The intention of this guide is to cover much of the primary foundations of C# that will boost your knowledge and prepare you for more in-depth learning!

Let’s get started!

About C#

Banner for About C Sharp

C# (pronounced C sharp) is one of the most popular programming languages in the world (and not to be confused with the C programming language). Developed by Microsoft more than 20 years ago, C# is built on top of the dotNET (.NET) Framework which is a free open-source, cross-platform developer platform for building different types of apps.

C# is an object-oriented, statically typed, general-purpose programming language widely used for:

  • Server-side web development using .NET
  • Desktop applications for Windows and macOS
  • Native mobile apps for iOS and Android using Xamarin
  • Microservices using Docker Containers
  • Cloud-based services
  • Machine Learning
  • Internet of Things
  • Game development for PC, Mac, Consoles, Mobile, and VR|AR with Unity

Banner for C Sharp Pros

Pros

C# is a statically-typed, object oriented programming language based on C which makes it very similar to other popular languages such as Java, C++, PHP, Swift, Objective-C and more. This means that once you learn one language, it would be very easy to understand and learn other programming languages.

Today, C# runs on .NET Core which is an open-source, cross-platform, high-performance, and scalable framework to build applications anywhere to run anywhere.

C# is a general-purpose, high-level, versatile, easy-to-learn programming language that when combined with technologies such as Xamarin for native mobile and desktop experiences and Unity for game development creates a powerful developer and execution experience.

There are a lot of great resources to help you code any app experience you want including courses, tutorials, code samples, and an active developer community.

Banner for C Sharp Cons

Cons

Most C# applications run on top of a Microsoft framework called .NET and for most of its life, this framework has been its best and worst feature. Originally .NET was a gigantic platform that Microsoft created to make it easy for developers to create powerful and complex applications. The framework allowed C# to be a relatively easy-to-learn language with low-level complex coding requirements (such as memory management) taken care of for us by the underlying framework. All of the languages that sat on top of .NET were compiled down (behind the scenes) to the same Microsoft Intermediate Language (known as MSIL). After that, .NET translated the MSIL code into a Just-in-Time language that computers could run. To make a long story short, C# was great as long as you were inside a Microsoft ecosystem.

Fast-forward to today and C# now only requires .NET Core which is an open-source, cross-platform, high-performance, and scalable framework to build applications anywhere to run anywhere. Combined with technologies such as Xamarin for native mobile and desktop experiences and Unity for game development, C# is a modern and versatile programming language and this con is largely a thing of the past.

Banner for C Sharp Getting Started

Getting Started with C#

Below you will find two options to start writing C# code quickly. The first is to set up a Desktop IDEIntegrated Development Environment (this will be important as you start to develop real apps). The second option is to learn the basics using an Online IDE (this option is great for learning since there is no setup required).

Desktop IDEIntegrated Development Environment

Writing C# code requires a code editor (often referred to as an IDEIntegrated Development Environment) and some basic setup which depends on the type of application you are creating and the associated technology you are using. For example, you may need to install the .NET framework, Xamarin for native mobile development or Unity for game development.

If needed, you can follow a video walkthrough of getting started with C# using Visual Studio Code by following the video instructions in the Learning Resources-Getting Started section below for Mac and Windows.

Online IDE – No Setup Required

For learning C# basics, you can use an in-browser IDE which requires no setup. For example:

    • Visit relpit.com
    • Press the Start Coding button
    • Login/signup
    • Press New repl (this is your project)
    • Select C# as your coding language
    • Provide your repl (project) with a name (such as “Learn C#”)
  • Press the Create repl button

Steps to Create a new repl on replit.com

You are now ready to begin! Write your code in the main.cs file (on the left) and press the Run button (in the top centre) to see your output in the console (on the right).

If needed, you can follow a video walkthrough of getting started with C# on replit.com by following the video instructions in the Learning Resources-Getting Started section below.

C# Console App – Hello World

The best way to learn a new language is to keep your learning environment as simple as possible. To learn the basics, we’ll create a simple C# Console Application on replit.com using the steps outlined above in the Getting StartedOnline IDE section. While a Console App is not the most exciting app in the world, it is a great way to learn the fundamentals!

Replit.com provides the following C# file, called main.cs, to get started:

using System;

class MainClass {
  public static void Main (string[] args) {
    Console.WriteLine ("Hello World");
  }
}

To begin, ignore everything but the command Console.WriteLine(“Hello World”). Notice that this command is located inside curly braces {}. Inside these braces is where we will write all our C# code. Later in this tutorial, we cover class and the other C# syntax inside the code block. It’s perfectly fine to ignore it for now.

Press the Run button at the top of the replit.com IDE and notice “Hello World” is printed in the Console.

Image showing the Run Button and Console Output in the replit.com IDE

Note: If you’re new to C# and have opted to set up a Desktop Environment, you may notice a flash on the screen instead of seeing your expected output in a console window (sometimes referred to as a terminal). What happens, in some cases, is that your C# console app runs, prints the output to the console, then the program stops execution. Depending on your setup, this may result in the console closing automatically. You can easily prevent this by adding Console.ReadKey() on the line following your last Console.WriteLine(). This command prevents the console from closing until you press a key (any key).

C# Syntax Basics

In the “Hello World” Console example above we displayed an image of how the Console output would look on replit.com. Given the many IDE options available and the fact that we advised ignoring the class syntax and surrounding C# code, for now, the examples in the C# Fundamentals sections that follow will show only the code between the curly braces. In addition, we’ll use C# Comments to show the expected results of our simple inputs and outputs. As an example, the code above would like this instead:

    Console.WriteLine("Hello World"); // Hello World

As we begin learning the fundamentals of C#, it’s important to keep these points in mind:

  • Every C# statement must end with a semi-colon ;
  • All blocks of C# code are within curly braces {}
  • C# is case sensitive: C is not equal to c

Banner for C Sharp Comments

Comments in C#

Comments are lines in your code that are ignored by C#. They serve several purposes:

  • They are used to leave notes for people (including future-you)
  • They are useful when debugging to tell C# to ignore one or more lines of code (without having to delete the lines of code)
  • They can be helpful when planning out a piece of logic you need to code (sometimes referred to as pseudocode)

C# comments syntax has two forms:

  • Use // for a single line comment (everything after on the same line is ignored by C#)
  • Use /* */ for a block comment (everything in between is ignored by C#)

// Comments in C#
// This is a comment
Console.WriteLine("Hello World"); // this is a comment
/*
This is a
block of 
comments.
These lines are
ignored by C#
Console.WriteLine("This line is not executed");
*/

Variables in C#

Variables are an essential element of any programming language. They provide a place to store data we may need to reference or update later. In C# each variable has a data type and a name. We store values in variables using the assignment operator.

Assignment Operator

In C# the assignment operator is the equal sign =. In its most basic form, this operator takes the value from the right side of the = and stores it in the variable on the left.

// Assignment Operator 
int b = 10; 
Console.WriteLine(b); // 10

Data Types

The data type tells C# what kind of data will be stored in the variable. The four basic data types are:

  • int (+/- integer)
  • double (+/- number containing decimals)
  • string (any character inside quotes)
  • bool (True or False)

The name, or identifier, allows us to refer to that specific variable anywhere in our code. When naming a variable, we can use any combination of letters, numbers, underscore or dollar sign with the following exceptions:

  • Names cannot be a C# keyword
  • Names cannot have whitespace
  • Names cannot start with a number

Let’s create variables to store each data type and print each variable’s value to the Console. We can declare a variable and assign a value at the same time or declare a variable and assign it a value later.

    int score = 5;
    double gravity = 9.81;
    string language;
    bool isLearningFun;

    language = "C#";
    isLearningFun = true;
    
    Console.WriteLine (score);          // 5
    Console.WriteLine (gravity);        // 9.81
    Console.WriteLine (language);       // C#
    Console.WriteLine (isLearningFun);  // True

There are three parts to creating a variable and assigning it a value, whether done together or separately. They are the data type (int), the name (score) and the value (5). Notice, we use the equal sign = to assign a value to a variable of any type.

Image showing a lot of numbers

Numbers in C#

C# has two basic number types:

  • int (+/- integer)
  • double (+/- number containing decimals)

These types are distinguished based on whether or not they can contain decimals.

Math Operators

Math in C# works the same as it does in the real world. The most common math actions have the following arithmetic operators:

  • +  addition
  •   subtraction
  • *  multiplication
  • /  division

    Console.WriteLine (2 + 5);  // 7
    Console.WriteLine (10 - 2); // 8
    Console.WriteLine (3 * 3);  // 9
    Console.WriteLine (20 / 2); // 10

Unary Operators

Another concept is known as Unary operators and they are very useful when writing code because they allow us to perform the common calculation of incrementing or decrementing by one in a much more code compact way.

// Unary Operator 
int a = 10; 
Console.WriteLine(a);   // 10
a = a + 1;
Console.WriteLine(a);   // 11
a--;
Console.WriteLine(a);   // 10
a++;
Console.WriteLine(a);   // 11

Math and Assignment Together

We can also use the assignment operator together with the arithmetic operators in a single command that modifies a variable’s value (by the value on the right) before storing it. This differs from the Unary operator which only increments/decrements by one.

// Assignment and Arithmetic Operators Together
int c = 1;
c += 10; 
Console.WriteLine(c); // 11

c -= 5;
Console.WriteLine(c); // 6

c *= 4;
Console.WriteLine(c); // 24

c /= 6;
Console.WriteLine(c); // 4

It’s important to note three rules regarding modifying and assigning a variable’s value:

  • Variables cannot be declared and modified at the same time
  • Variables cannot be modified without including the assignment operator =
  • The arithmetic operator must come before the assignment operator +=

Order of Operations

Math in C# follows the same rules as regular math.

  1. Parenthesis first (3 + 2 )* 5 – 4
  2. Then multiplication and division (from left to right)
  3. Then addition and subtraction (from left to right)

// Order of Operations
int ooo = (3 + 2 )* 5 - 4;
Console.WriteLine (ooo); // 21

Banner for C Sharp Strings

Strings in C#

Required Syntax

To assign text to a variable we use double quotes “…”. Anything inside the quotation marks is considered text. This includes numbers and symbols as well as uppercase/lowercase letters. In its most basic form it looks like this:

string userName = "aBc_123";

It’s important to note that we must use double quotation marks ( “…” ) – anything else will cause an error.

Escape Characters

Having to use double quotes presents an issue if you want to use double quotes within your text string such as using a quote or dialogue. For example:

// Escape Characters
string dialogue = "When the player scored, his teammates shouted "We Win!"";

Console.WriteLine(dialogue);

If you run this code, the C# compiler generates an error. This is because the quotation marks close and open the string around “When the player scored, his teammates shouted “ and an empty string at the end “” leaving We Win! not within any quotes. C# does not know what to do with these characters so it throws an error.

To fix this we have to use something called escape characters. To do this we place the backslash \ symbol before the quotation marks \” we want to keep as part of the text string. The corrected code looks like this:

// Escape Characters
string dialogue = "When the player scored, his teammates shouted \"We Win!\"";

Console.WriteLine(dialogue); // When the player scored, his teammates shouted "We Win!"

String Methods

In C#, there are many operations we can perform on strings. These operations are known as string methods. C# has more than 40 string methods including operations to compare strings, find strings within strings, combine strings, format values, and more. Some methods are called on string variables while others are called against the C# String Class itself.

String Variable Methods

Some methods are called on a string variable such as ToUpper() and ToLower(). Using these methods we can:

  • Display a value as upper or lowercase without changing its value
  • Change the variable’s value using the assignment = operator

// Variable Methods
string caseExample = "Case!";
Console.WriteLine(caseExample);             // Case!

// Display Only - Value Not Changed
Console.WriteLine(caseExample.ToUpper());   // CASE!
Console.WriteLine(caseExample.ToLower());   // case!
Console.WriteLine(caseExample);             // Case!

// Value Changed
caseExample = caseExample.ToUpper();
Console.WriteLine(caseExample);             // CASE!
caseExample = caseExample.ToLower();
Console.WriteLine(caseExample);             // case!

String Class Methods

Some methods are called on the C# String Class such as String.Concat()

Strings can be combined in multiple ways including:

  • + sign
  • String.Concat() method

When combining strings:

  • You can use any combination of variables and string literals ( “…” )
  • You can use any combination of letters, numbers, and symbols (it all becomes text)
  • Combining strings does not automatically add space (but you can add it yourself)

// Class Methods
string hello = "Hello";
string world = "World";
int num = 1;

string HelloWorld;
// Join strings together with + sign
HelloWorld = hello+world+num+"!";
Console.WriteLine(HelloWorld);        // HelloWorld1!
HelloWorld = hello+" "+world+num+"!";
Console.WriteLine(HelloWorld);        // Hello World1!

// Join strings together with String Method Concat
HelloWorld = String.Concat(hello,world,num,"!");
Console.WriteLine(HelloWorld);        // HelloWorld1!
HelloWorld = String.Concat(hello," ",world,num,"!");
Console.WriteLine(HelloWorld);        // Hello World1!

String Length

If you need to know the length of a string, C# has a string property called Length.

// String Length
string helloWorld = "Hello World!";

int len = helloWorld.Length;

Console.WriteLine(len);  // 12

Notice that the length includes spaces. Also, note that Length is a property and therefore has no parens () after it like string methods do.

Various technology objects overlayed with binary

Booleans in C#

Boolean ( bool ) is the simplest data type because it can only have one of two values: True or False.

// Boolean Data Type
bool isLearningFun = true;

Console.WriteLine(isLearningFun); // True

This idea of true|false, yes|no, correct|not-correct, equal|not-equal, on|off, 0|1 and so on is really the essence of how computers work. That makes this simple data type very important in coding. Understanding what conditions return True or False will be very important when you learn C# Decision Control.

As is usually the case with programming, syntax is very important. Note that the exclamation point ! comes before the equal sign = to create !=. Coding these operators and those in the upcoming sections in reverse will throw an error. For now, let’s consider some of the situations that return a Boolean result.

Equality Operators

The equality operators check if two numbers are equal or not equal.

bool boolean1 = 2 == 2; // True
bool boolean2 = 1 == 4; // False

Notice that == is a comparison operator and different from the single equals = which is the assignment operator. In this case, the condition is evaluated and then the result is assigned to the bool variable on the left.

To check directly for inequality we use the exclamation point ! in front of the equal sign != as follows:

bool boolean1 = 2 != 2; // False
bool boolean2 = 1 != 4; // True

Notice that we get the exact opposite results as above.

Relational Operators

Relational operators are used for comparing two numbers beyond simple equality. These operators are:

  • > greater than
  • < less than
  • >= greater than or equal to
  • <= less than or equal to

bool booleanValue1 = 1 > 4;   // False
bool booleanValue2 = 2 < 3;   // True
bool booleanValue3 = 3 >= 2;  // True
bool booleanValue4 = 4 <= 1;  // False

Multiple Conditions

In C#, we have two ways to check more than one condition at a time. They are:

  • AND ( && )
  • OR ( || )

bool isTrue1 = 3 == 3 && 4 == 4;  // True
bool isTrue2 = 3 >= 3 && 4 >= 4;  // True
bool isTrue3 = 3 >= 3 && 4 < 4;   // False
bool isTrue4 = 3 > 3 || 4 == 4;   // True
bool isTrue5 = 3 > 3 || 4 > 4;    // False

For AND ( && ) both conditions must be True in order for the result to be True. If the first comparison returns False, the second condition is not checked and False is returned. If the first condition returns True then the second condition is checked and its result determines what is assigned to the variable on left.

For OR ( || ) either condition can be True in order for the result to be True. Only if both conditions are False, will False be assigned to the variable on left.

Banner for C Sharp Arrays

Arrays in C#

So far we’ve had a one-to-one match between variables and values. But what if you wanted to store a list of items such as your to-do list, your favourite movies or a player’s inventory of weapons in a game? You could store each item inside its own variable but that could get out of hand very quickly and would not be very flexible. It would great if we could store those lists of related items in a single variable! This is a great use-case for Arrays. Arrays allow you to store multiple values in a single variable.

Array Syntax

The syntax for an array starts with the type of data we want to store in the array followed by square brackets. If we want to store a list with a data type of string then we would code string[]. This tells C# we want to store an array instead of a single string value. We next code the name of the variable and the assignment operator ( = ) as we have done for other variables. Our actual list is stored within curly braces {} with each item separated by a comma. For example, a list of colour names (string data type) would be coded like this:

// Arrays in C#
string[] favColours = {"red", "green", "blue", "purple", "orange"};

It’s important to know that all items in an array must be the same data type.

Declaring Arrays

If we know the exact items we want to store in the array we can construct it as above. However, we can also construct dynamic arrays and this feature is what makes arrays powerful.

If we know the number of items our array will hold, we just don’t know the values, then we can declare it like this:

string[] items = new string[5];

This creates an empty array sized to hold five items. We put the length of the array inside the square brackets [5]. It’s important to know that this size cannot be changed later so we may want to create longer arrays depending on what we plan to store.
// Arrays
int[] cards = new int[52];
double[] prices = new double[100];
string[] names = new string[150];

Referencing Array Items

You can think of an array like a table where the first column is the array’s index. The index is the position of an item within the array. It’s important to note that the first item always has an index of zero. We reference array items by using the name of the array followed by the item index inside square brackets. For example:

// Referencing Array Items
string[] favColours = {"red", "green", "blue", "purple", "orange"};

Console.WriteLine(favColours[0]);   // red
Console.WriteLine(favColours[2]);   // blue
Console.WriteLine(favColours[4]);   // orange

We can also store a selected item in another variable such as:
// Storing an Array Item
string[] favColours = {"red", "green", "blue", "purple", "orange"};

string selectedColour = favColours[2];
Console.WriteLine(selectedColour);  // green

Array Length

It’s very common to need to know the length of an array. We find the length using the Array’s Length property.

string[] favColours = {"red", "green", "blue", "purple", "orange"};

// Array Length
Console.WriteLine(favColours.Length); // 5

It’s important to know that empty spaces count towards the array’s length.
// Empty Array
int[] cards = new int[52];
// Array Length
Console.WriteLine(cards.Length);    // 52

Learning Resources

We’ve helped you through a lot of basics – from variables to operators, and all the way to arrays. These materials will help with storing and controlling your data in a lot of ways. However, there is a ton more to learn (like multidimensional arrays, which we didn’t have remote time to cover)! If you want, you can dive to our companion post here, which helps cover a lot more fundamentals for C# programming logic. Or, you can dive into one of the links below and get started with a more in-depth look at C#!

Ending Words

As with any programming language, there is a seemingly endless amount you could learn. After all, we haven’t even touched on object oriented programming here.

While we’ve given you the resources above, remember the best way to truly learn more is by writing C# code in your own apps or games. However, with this guide, we hope you’ve absorbed key fundamentals that will help you dive into further C# topics! You can only benefit by learning C#, so we hope you’ll continue whether you want to create robust software for your career or make entertaining games as a hobby.

Enjoy the journey! Happy Coding!

ON SALE – FINAL DAYS
BUILD GAMES
BUILD YOUR OWN GAMES

✓ 250+ coding courses

✓ Interactive lessons

✓ Guided learning paths

✓ Help from expert mentors

GET IT ALL FOR JUST
$1