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.
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.
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, ...).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With