C# With Tutorial – Complete Guide

Beginning a journey into the world of coding can sometimes feel daunting. The landscape of languages, libraries and tools to choose from can seem overwhelming. However, today, dear reader, we’ll accompany you on a decidedly exciting adventure – an introduction to C# (C sharp). If you’re wondering where to start, or looking to strengthen your programming foundations, then rest assured, you’re in the right place.

Understanding C#

C# is a modern, general-purpose, object-oriented programming language developed around the year 2000 by Microsoft Corporation. It’s one of the most prevalent languages in the programming-world today.

Applications of C#

“Why should I learn it?”, you might ask. The applications of C# are wide and varied. From building sophisticated enterprise-level server applications to new age mobile apps, C# finds its place everywhere.

Why Learn C#?

Moreover, it’s especially essential for anyone who wants to delve into the world of game development, as C# is the recommended language for creating games with Unity engine. Learning C# could therefore open the door to potential employment opportunities within this industry, not to mention, the sheer excitement of being able to program your own game!

Now that we’ve looked at the ‘what’ and ‘why’, let’s get our hands dirty and delve into the nitty-gritties of learning ‘how’ in the coming sections. We’ll start off with some basic examples and progressively move to more complex ones. Time to have some fun with coding!

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

C# Basics

Just like starting anything new, it’s best to begin at the basics with C#. Let’s cover some of the fundamental aspects, like defining variables, conditional statements, and loops.

First, let’s declare a variable in C#. Pay attention to how we have to define the type of the variable before the variable name itself.

int myVar = 10;

In this example, ‘int’ is the type of variable, ‘myVar’ is the name of the variable, and ’10’ is the value assigned to ‘myVar’.

Next, we’re going to look at conditional statements in C#. These are used to perform different actions based on different conditions.

int myVar = 10;
if (myVar == 10) 
{
  Console.WriteLine("Value of myVar is 10");
}
else 
{
  Console.WriteLine("Value of myVar is not 10");
}

In the code above, if the condition within the ‘if’ statement (myVar == 10) is true, then the code within the ‘if’ block will run. If it’s false, the code within the ‘else’ block will run.

Let’s move on to loops. A loop allows us to execute a block of code several times.

for(int i=1; i<=5; i++) 
{
  Console.WriteLine("Hello, World!");
}

In this example, the Console.WriteLine command will be executed 5 times, printing out “Hello, World!” each time.

C# Functions

A function is a block of code designed to perform a particular task. It improves code reusability and makes it more readable.

Here’s how to declare a simple function in C# that calculates the sum of two numbers.

public int Add(int num1, int num2) 
{
  return num1 + num2;
}

Also, here’s an example of how you can call a function:

int sum = Add(5,10);
Console.WriteLine(sum);

In this code snippet, the function ‘Add’ is called with 5 and 10 as arguments. The function returns their sum, which is stored in the variable ‘sum’ and subsequently printed out.

Working with Arrays and Lists in C#

Arrays and Lists in C# provide excellent ways to store multiple related items of the same type together.

Here’s how to declare an array and add elements using C#.

int[] myArray = new int[5] {1, 2, 3, 4, 5};

In this example, we’ve declared an integer array named ‘myArray’, and it can hold five elements.

Next, we’ll take a look at lists. Unlike arrays, lists can change in size.

A list is created in C# like this:

List myList = new List();
myList.Add(1);
myList.Add(2);
myList.Add(3);

In our example, we instantiate a new List of integers, then add the elements 1, 2, and 3 to it.

C# Exception Handling

While writing code, it’s common to come across errors. In C#, we can handle these errors and exceptions gracefully using try, catch, and finally blocks.

try 
{
  int num = 10 / 0;
}
catch (DivideByZeroException e) 
{
  Console.WriteLine("Exception Caught: " + e);
}
finally 
{
  Console.WriteLine("But life goes on!");
}

We are intentionally trying to perform a division by zero here, which will cause an exception. The catch block will intercept this exception and print a message, and the finally block will execute at the end, regardless of whether an exception occurred or not.

Classes and Objects in C#

An important aspect of C# is Object-Oriented Programming (OOP) which is implemented using classes and objects. Let’s create a simple class named ‘Animal’.

public class Animal 
{
  public string name;
  public int age;

  public Animal(string name, int age) 
  {
    this.name = name;
    this.age = age;
  }

  public void Speak() 
  {
    Console.WriteLine("I am an animal named " + name);
  }
}

This class has two attributes: name and age, and a method called ‘Speak’.

An instance of this class is created as follows:

Animal myDog = new Animal("Charlie", 3);
myDog.Speak();

Here, we create a new Animal object called ‘myDog’, providing “Charlie” and 3 as arguments, which are used to initialize the object’s attributes. When the ‘Speak’ method is called, it outputs “I am an animal named Charlie”.

Remember, every programming journey begins with a single “Hello, World!” With persistence and patience, you’ll be creating complex applications and games in C# before you know it. Happy coding!

C# Inheritance

Inheritance is one of the primary principles of Object-Oriented Programming. A class can inherit members (fields, methods, etc.) from another class, promoting reusability and organization.

Consider the ‘Animal’ class we created earlier. Here’s how we create a ‘Dog’ class that inherits from it:

public class Dog : Animal 
{
  public string breed;

  public Dog(string name, int age, string breed) : base(name, age) 
  {
    this.breed = breed;
  }

  public void Bark() 
  {
    Console.WriteLine("Woof!");
  }
}

In this snippet, the ‘Dog’ class extends ‘Animal’, inheriting the properties and methods (‘name’, ‘age’, and ‘Speak’ method), and also adds a new property called ‘breed’. It introduces a new method called ‘Bark’. The base keyword is used to call the constructor of the base class.

Here’s an example of creating a ‘Dog’ object:

Dog myDog = new Dog("Max", 5, "Beagle");
myDog.Speak();
myDog.Bark();

The newly created ‘Dog’ object, ‘myDog’, has properties ‘name’, ‘age’, and ‘breed’. It can also call ‘Speak’ method (inherited from the ‘Animal’ class) and its own ‘Bark’ method.

Multithreading in C#

Multithreading allows a program to execute multiple threads concurrently. It’s instrumental in creating more efficient, responsive applications.

Here’s how to create a new thread and print a message:

using System.Threading;

Thread myThread = new Thread(() => 
{
  for (int i = 0; i < 10; i++) 
  {
    Console.WriteLine("Hello from new thread");
  }
});
myThread.Start();

In this example, we create and start a new thread which runs a loop to print a message 10 times.

Generics in C#

Generics allow you to define type-safe data structures, without committing to actual data types. They increase code reusability and performance.

Here’s an example of a generic ‘MyGenericClass’ that uses a type placeholder ‘T’:

public class MyGenericClass 
{
  public T GenericProperty { get; set; }
}

An instance of this generic class can be created like this:

MyGenericClass myGenericInt = new MyGenericClass();
myGenericInt.GenericProperty = 5;

MyGenericClass myGenericString = new MyGenericClass();
myGenericString.GenericProperty = "Hello, World!";

In this example, we’ve created two instances of ‘MyGenericClass’: one using an integer type, and another using a string type.

Keep practicing and expanding your C# knowledge, as there are many more topics to explore, such as LINQ, delegates, and asynchronous programming, to name just a few. With every new concept mastered, you’re one step closer to becoming a versatile C# programmer, capable of creating a diverse range of applications and games. Happy learning!

Keep Going! Your Next Steps in Becoming a C# Master

At this point in your journey, you’re equipped with the basics of C# programming and probably eager to apply your newfound skills in inspiring ways. Where should you venture next, you ask? Why not leap into the exhilarating realm of game development?

At Zenva, we offer a wealth of resources, one of which is our Unity Game Development Mini-Degree. It’s a comprehensive suite of project-based courses designed to get you familiar with game development using Unity, a globally sought-after skill in many industries ranging from education to architecture. Whether you’re a novice or an experienced developer, our mini-degree is structured flexibly to cater to all levels.

You might also like to explore our entire Unity Collection for a broader selection of top-rated courses. We’re committed to making your learning experience as interactive as possible with challenges and quizzes helping bolster your skill set.

Encourage your curiosity about coding and game creation to guide you. Remember, every step on this path, no matter how small, takes you closer to becoming an accomplished programmer. Let’s continue this journey together. Happy coding!

Conclusion

Your journey into C# programming has only just begun, and yet, you may already perceive the wealth of opportunities this skill offers. From building interactive websites to crafting immersive video games, your newly acquired abilities can unlock an array of creative possibilities that seemed beyond reach before.

With Zenva, you’ve engaged with a trusted and experienced guide ready to accompany you throughout your entire learning journey. We invite you to continue exploring with us in our Unity Game Development Mini-Degree, perfect for turning your game development dreams into reality. Adventure awaits you in the world of coding – dare to unearth your limitless potential with us!

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.