Sunday, 23 November 2014

C#.NET Tutorial - Day - 13 - Classes - Constructors & Destructors


CONSTRUCTORS & DESTRUCTOR



CONSTRUCTORS



Constructors are special methods, used when instantiating a class. A constructor can never return anything, which is why you don't have to define a return type for it. A normal method is defined like this:




A constructor can be defined like this:





In our example for this post, we have a Car class, with a constructor which takes a string as argument. Of course, a constructor can be overloaded as well, meaning we can have several constructors, with the same name, but different parameters. Here is an example:





A constructor can call another constructor, which can come in handy in several situations. Here is an example:





If you run this code, you will see that the constructor with no parameters is called first. This can be used for instantiating various objects for the class in the default constructor, which can be called from other constructors from the class. If the constructor you wish to call takes parameters, you can do that as well. Here is a simple example:





If you call the constructor which takes 2 parameters, the first parameter will be used to invoke the constructor that takes 1 parameter. 




DESTRUCTORS



Since C# is garbage collected, meaing that the framework will free the objects that you no longer use, there may be times where you need to do some manual cleanup. A destructor, a method called once an object is disposed, can be used to cleanup resources used by the object. Destructors doesn't look very much like other methods in C#. Here is an example of a destructor for our Car class:





Once the object is collected by the garbage collector, this method is called.



No comments:

Post a Comment