Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there really any need for constructors or destructors in c#?

Can you tell me is there any need for constructors in c# where properties are available to set default values?

Again, is there any need for destructors where the language is garbage collected?

Please give me some practical examples.

like image 587
user366312 Avatar asked Dec 10 '22 05:12

user366312


2 Answers

Constructors are essential to initialize immutable data. They also help with declaring IoC/DI expectations/demands. For scenarios where there is a minimal set of required data to configure an object, it is useful to demand it as early as possible - which often means the constructor.

Destructors/finalisers are used generally to release unmanaged resources - for example OS handles, or memory from the unmanaged area (Marshal.AllocHGlobal). These resources are not garbage collected, so care must be taken to release them manually - else a leak occurs, or you saturate limited pools. Such examples are pretty rare in application code, and are almost always used as a fallback in addition to IDisposable - for when it doesn't get disposed correctly.

like image 123
Marc Gravell Avatar answered May 17 '23 23:05

Marc Gravell


Can you tell me is there any need for constructors in c# where properties are available to set default values?

There are cases where you would explicitly specify that the class requires some dependency in order to work. In this case you could use constructor injection:

public class MyClass
{
    private readonly ISomeDependency _dependency;
    public MyClass(ISomeDependency dependency)
    {
        _dependency = dependency;
    }

    ... some methods that require the dependency.
}

Now the author of the class explicitly states that this class needs some dependency in order to work properly, so in order to instantiate it you need to provide this dependency.

Again, is there any need for destructors where the language is garbage collected?

The language is garbage collected as long as it is managed code. But in managed code you could use P/Invoke to call unmanaged code. And unmanaged code is obviously no longer garbage collected. So you could use destructors to release resources hold by unmanaged code (things like unmanaged handles, unmanaged memory allocations, ...).

like image 34
Darin Dimitrov Avatar answered May 17 '23 22:05

Darin Dimitrov