C# Classes Tutorial

Intro

In C#, a class is a user-defined type which can be used to create objects, representing the base of OOP. A class can’t be used directly, so you need to create an instance:

MyClass – is the name of the class
MyObject – is the name of the object that uses that class.

Creating a class

Let’s start with a pretty straightforward example: we have a list of cars, each car has some properties (like speed and color) and some basic actions/functions (like moving or stopping). But how can we store all this data ? Here the classes become useful.
We’ll create a class called ‘car’:
* every element in the class must be public in order to be accessible from the outside

Now let’s say we have 10 cars available, so we need 10 instances of our C# class: we can use an array for this:

Using the instances of the class

As I said before, every element has it’s own instance, they will NOT share any data. To assign a property for an object you can do something like this:

Constructors

If you’ve understood everything above, we can move to a more complex element: constructors.
A constructor is a block called when an instance of the class is created – even if it looks like a function, it has no type (it’s not void or anything else) and also must have the exact name of the class (the class and the constructor must share the same name). We’ll use the ‘car’ class again, but with some modifications:

The constructor above is called whenever you create an instance (object) :

Destructors

Destructors (also called finalizers) are used to release the memory you’ve been using while you had an instance. They’re automatically called when program’s closing – however they can’t be called manually.
One thing to note: they don’t take any parameters.
Because of C#’s memory management, you don’t really need to use them unless you’re working with unmanaged code. Most of the times, you won’t need to use them.
This is how you declare a destructor for a class:
C#
1
2
3
4
5
6
7
8
public class car
{
     ~car()  
     {
          // clear memory
     }
}
Previous
Next Post »