Constructors are special methods that are used when using a class immediately. A producer can never return anything, this is the reason why you do not have to define a return type for it. A general method is defined as:
ublic string Describe()A constructor can be defined like this:
public Car()In our example for this chapter, we have a car Class, in which there is a constructor, which takes the string as a logic. Of course, a constructor can also be overloaded, which means that we can make many constructors with the same name, but different parameters are an example here:
public Car() { } public Car(string color) { this.color = color; }A constructor can call another constructor, which can come in handy in several situations. Here is an example:
public Car() { Console.WriteLine("Constructor with no parameters called!"); } public Car(string color) : this() { this.color = color; Console.WriteLine("Constructor with color parameter called!"); }If you run this code, you will see that the constructor with a parameter is not previously called. It can be used in the default constructor for the various objects for the class, which can be told from other class constructors. If constructors take the parameters you want to call, then you can do that too. Here is a simple example:
public Car(string color) : this() { this.color = color; Console.WriteLine("Constructor with color parameter called!"); } public Car(string param1, string param2) : this(param1) { }
Destructors
Since C # garbage collects, given that the framework will free those items you no longer use, there may be times where you need to make manual confirmation. A destroyer, once an object that is disposed of, an object is used, can be used to clean the resources used by the object. Destructors do not look very much like other methods in C #. Here is an example of a disaster for our car class:
~Car() { Console.WriteLine("Out.."); }
0 comments:
Post a Comment