C# In Tutorial – Complete Guide

Welcome to a new adventure in the realm of programming! Today, we’re going to delve into the fascinating topic of C#. This powerful and versatile programming language is the cornerstone for many applications, the most exciting of which are video games. As a language, C# is a tool you can use to bring your creative ideas to life, and it is more accessible than you might think.

What is C#?

C# (pronounced “C Sharp”) is a modern, object-oriented programming language developed by Microsoft. It is part of the .NET platform, and it’s widely used in a variety of applications. From web services to desktop apps and mobile development, C# has you covered. But where it truly shines is in game development, thanks to its integration with the powerful Unity game engine.

Why Should I Learn C#?

Learning C# opens a world of opportunities. It’s a sought-after skill in the tech industry, increasing your job prospects and salary potential. But beyond the career benefits, C# is a key to a universe of creativity.

As the primary language used in Unity, one of the most popular game engines in the world, C# allows you to create interactive experiences, from simple 2D mobile games to sprawling 3D titles for consoles and PCs. Knowledge of C# can transform you from game player to game creator.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Getting Started with C#

The most basic part of any programming language is writing a simple output to the console. In C#, we do this with the ‘Console.WriteLine()’ command. This will write a line of text to the console window.

// Outputs "Hello, World!" to the Console
using System;
class Program {
    static void Main() {
        Console.WriteLine("Hello, World!");
    }
}

C# programs are created around classes and methods. In our example, the ‘Program’ class contains our ‘Main’ method, which executes our ‘Console.WriteLine()’ command when the program runs.

Using Variables and Data Types in C#

Variables are fundamental to any programming language, allowing us to store values for use in our programs. In C#, we declare variables with a data type before we use them.

// Declaring and initializing a string variable
string name = "Zenva";
Console.WriteLine(name);
// Outputs: Zenva

C# supports several data types, such as integer (int), floating point number (float), boolean (bool) and others.

// Declaring an integer variable
int year = 2021;
Console.WriteLine(year);
// Outputs: 2021

// Declaring a float variable
float pi = 3.14f;
Console.WriteLine(pi);
// Outputs: 3.14

// Declaring a bool variable
bool isLearning = true;
Console.WriteLine(isLearning);
// Outputs: True

Flow Control with If-Else Statements

If-Else statements in C# allow us to perform different actions based on different conditions.

// "if" statement in C#
using System;
class Program {
    static void Main() {
        int num = 10;
        if (num > 5) {
            Console.WriteLine("Number is greater than 5");
        } else {
            Console.WriteLine("Number is 5 or less");
        }
    }
}
// Outputs: Number is greater than 5

The ‘else if’ clause lets us specify a new condition if the first one is not met.

// "else if" statement in C#
using System;
class Program {
    static void Main() {
        int num = 10;
        if (num > 15) {
            Console.WriteLine("Number is greater than 15");
        } else if (num > 10){
            Console.WriteLine("Number is greater than 10 but less than 15");
        } else {
            Console.WriteLine("Number is 10 or less");
        }
    }
}
// Outputs: Number is 10 or less

Loop Control with For and While Statements

Loops are another essential part of any programming language and in C#, we have ‘for’ and ‘while’ loops to execute a block of code repeatedly. Let’s see examples of both.

#### For Loop Example:

// "for" loop in C#
using System;
class Program {
    static void Main() {
        for (int i = 0; i < 5; i++) {
            Console.WriteLine(i);
        }
    }
}
// Outputs: 0, 1, 2, 3, 4

A ‘for’ loop has three components: the initialization, the condition, and the iterator. In the above example, we start with ‘i’ equal to zero. As long as ‘i’ is less than 5, we print ‘i’ and then increment it by 1.

#### While Loop Example:

// "while" loop in C#
using System;
class Program {
    static void Main() {
        int i = 0;
        while (i < 5) {
            Console.WriteLine(i);
            i++;
        }
    }
}
// Outputs: 0, 1, 2, 3, 4

In the ‘while’ loop, we first set ‘i’ to zero. As long as ‘i’ is less than 5, we print ‘i’ and then increment it by 1. It’s important to remember to increment ‘i’, otherwise the loop will run indefinitely.

Functions in C#

Functions are a block of reusable code that carries out a task. In C#, functions are defined inside a class. Let’s look at an example:

// Function in C#
using System;
class Program {
    static void Main() {
        SayHello();
    }

    static void SayHello() {
        Console.WriteLine("Hello, Zenva!");
    }
}
// Outputs: Hello, Zenva!

Our ‘SayHello’ function prints “Hello, Zenva!” onto the console. We call this function in our ‘Main’ method, which is run when our application starts.

Functions in C# can also accept parameters and return a value. Parameters are data passed into the function, and the return value is the result of the function’s calculations. For example:

// Function with parameters and a return value
using System;
class Program {
    static void Main() {
        int result = AddNumbers(5, 10);
        Console.WriteLine(result);
    }

    static int AddNumbers(int num1, int num2) {
        int sum = num1 + num2;
        return sum; 
    }
}
// Outputs: 15

In this case, ‘AddNumbers’ is a function that takes two integers as parameters. It adds these two numbers together and returns the sum.

These are just the basics. C# is an expansive language with a lot to offer. With practice, you’ll enable your aspirations in game development, mobile apps, or whichever path your creativity leads you.

C# Data Structures

Beyond basic variables, C# has a range of data structures for organizing and storing data in different ways. These include arrays, lists, and dictionaries.

#### Arrays:

Arrays in C# are used to store multiple variables of the same type in a single data structure.

// Array in C#
string[] fruits = new string[] {"apple", "banana", "cherry"};
Console.WriteLine(fruits[1]);
// Outputs: banana

#### Lists:

While arrays are useful, they have a fixed size. When you need a collection that can change size, you can use a List.

// List in C#
using System.Collections.Generic;
List fruits = new List();
fruits.Add("apple");
fruits.Add("banana");
fruits.Add("cherry");
Console.WriteLine(fruits[1]);
// Outputs: banana

Classes and Objects

C# is an object-oriented programming language, which means it uses classes to define objects’ properties and behavior. An object is an instance of a class.

// Class in C#
public class Fruit {
    public string name;
    public string color;

    public Fruit(string fruitName, string fruitColor) {
        name = fruitName;
        color = fruitColor;
    }
}

// Object in C#
Fruit apple = new Fruit("Apple", "Red");
Console.WriteLine(apple.name);
// Outputs: Apple

Exception Handling with Try-Catch

Exceptions are unexpected errors that can occur during the execution of your program. C# provides a way to handle these errors gracefully using a try-catch block.

// Try-Catch in C#
try {
    int result = 10 / 0;
}
catch (DivideByZeroException ex) {
    Console.WriteLine("An error occurred: " + ex.Message);
}
// Outputs: An error occurred: Attempted to divide by zero.

Here, we’re attempting to divide by zero, which will throw a ‘DivideByZeroException’. The ‘catch’ block catches this exception and prints a helpful error message to the console.

In Conclusion…

C# is an incredibly rich and powerful language that lays at the heart of many applications. Whether you’re using it in game development with Unity, building mobile apps with Xamarin, or creating web applications with ASP.NET, C# provides the structure and flexibility your projects need.

Today, we’ve just scratched the surface of C#, but hopefully, these examples have piqued your interest in further exploration. Join us in exploring more about C# and transform yourself from a gaming enthusiast into a skilled game developer.

Where to go next?

Exploring C# is both fascinating and rewarding, but we’ve only touched the surface today. What if you could take your new understanding of C# and use it to create engaging, immersive games? By combining your C# knowledge with a powerful game engine like Unity, the gaming world is yours to create!

At Zenva, we’ve got just the thing to help you on this journey – our comprehensive Unity Game Development Mini-Degree. This mini-degree is a collection of courses suitable for beginners and skilled learners alike. It covers essential topics such as game mechanics, animation, and audio effects. By the end of it, you’ll have a portfolio of Unity projects showcasing your skills.

You can also explore our broader collection of learning content for Unity. Whichever path you choose, we are here to help you bridge the gap between beginner and professional. Remember, learning is a continuous journey. Keep exploring, keep coding!

Conclusion

Armed with the power of C# and the right training, you are poised to step into the captivating field of Unity game development. The journey will be exciting, innovative, and ultimately rewarding as you bring your unique visions to life. Every great game starts with a single line of code – so why not let it be yours?

Here at Zenva, we’re eager to be your guide on this exciting journey. Our Unity Game Development Mini-Degree provides comprehensive, immersive training that will take your C# understanding and turn it into tangible, creative results. Get ready to level up your skills and transform your gaming experiences. Happy coding!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.