C# language: 9. Constructors and destructors

in #programming7 years ago

CC.png

We learned the methods recently, today we will know constructors and destructors.

Constructors

Constructors were created for convenient initialization of fields in classes, it is as a special method is the same name as the class but returns nothing, constructor can’t be inherited (we will learn about inheritance later), it is called automatically when creating the object.

So far, we’ve initialized variables in the Cake class like this:

Console.WriteLine("Enter the amount of salt");
cake.AmountOfSalt= double.Parse(Console.ReadLine());
 
Console.WriteLine("Enter the baking time");
cake.BakingTime = int.Parse(Console.ReadLine());
 
Console.WriteLine("Enter the amount of eggs");
cake.NumberOfEggs = int.Parse(Console.ReadLine());
 
Console.WriteLine("Enter the amount of liters of milk");
cake.HowMuchMilk = int.Parse(Console.ReadLine());
 
Console.WriteLine("Enter the amount of flour");
cake.HowMuchFlour = int.Parse(Console.ReadLine());

However, you will admit that it is not very convenient

You can do the same in the constructor:

public Cake(double AmountOfSalt, int BakingTime, int NumberOfEggs, int HowMuchMilk, int HowMuchFlour)
{ 
    amountOfSalt = AmountOfSalt;
    bakingTime = BakingTime;
    numberOfEggs = NumberOfEggs;
    howMuchMilk = HowMuchMilk;
    howMuchFlour = HowMuchFlour;
}

I’m explaining what’s going on

in brackets we give the values we gave in the Main function in turn:

Cake cake = new Cake(double.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()),
 int.Parse(Console.ReadLine()), int.Parse(Console.ReadLine()));

These values, which we have given in brackets in the Main function, go to the constructor and assign them to the properties for the validation to take place.

Destructors

For example, in C ++ you had to manually use the destructor to prevent memory leakage, but in C # this is done for us by a .Net mechanism called Garbage Collector.

However, it is worth remembering that each class has only one destructor, which can not be inherited or overloaded, to which we do not provide arguments, and which does not return anything, and we do not give any access modifier – and so the destructor will be called by Garbage Collector.

So in short, you probably will not need to use destructors in C #. 🙂

This content also you can find on my blog http://devman.pl/csharplan/c-language-9-constructors-destructors/

If you recognise it as useful, share it with others so that others can also use it.

Leave upvote and follow and wait for next articles :) .

That’s it, bye!

Coin Marketplace

STEEM 0.17
TRX 0.24
JST 0.034
BTC 95807.92
ETH 2778.70
SBD 0.68