简体   繁体   中英

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.

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, ...).

One example where a constructor is absolutely necessary is with immutable types. How else would your fields get their value?

Finalizers(Spec calls them destructors, but that's utterly stupid IMO) are usually only necessary when working with unmanaged resources. But in most cases a critical finalizer (using the SafeHandle class family) is the correct choice for these.

The Dispose() method in useful when working with unmanaged resources, but also if you need to do something on destruction, such as unsubscribing from events. It's also used together with using to create an inferior version of RAII.

A constructor can be used, where every time an object gets created and if we want some code to be executed automatically. The code that we want to execute must be put in the constructor. The general form of a C# constructor is as follows

modifier constructor_name (parameters)
{
  //constructor body
}

The modifiers can be private,public, protected or internal.The name of a constructor must be the name of the class, where it is defined. A constructor can take zero or more arguments. A constructor with zero arguments (that is no-argument) is known as default constructor. Remember that there is not return type for a constructor.

The following class contains a constructor, which takes two arguments.

class Complex
{
  private int x;
  private int y;
  public Complex (int i, int j)
  {
    x = i;
    y = j;
  }
  public void ShowXY ()
  {
     Console.WriteLine(x + "i+" + y);
   }
} 

The following code segment will display 20+i25 on the command prompt.

Complex c1 = new Complex (20,25);
c1.ShowXY (); // Displays 20+i25

That is when we create the object of the class Complex, it automatically calls the constructor and initializes its data members x and y. We can say that constructor is mainly used for initializing an object. Even it is possible to do very complicated calculations inside a constructor. The statement inside a constructor can throw exceptions also.

Destructors

The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory occupied by the un-used objects. The destructor implements the statements to be executed during the garbage collection process. A destructor is a function with the same name as the name of the class but starting with the character ~.

Example:

class Complex
{
  public Complex()
  {
      // constructor
  }
  ~Complex()
   {
       // Destructor
    }
 }

Remember that a destructor can't have any modifiers like private, public etc. If we declare a destructor with a modifier, the compiler will show an error.Also destructor will come in only one form, without any arguments. There is no parameterized destructor in C#.

Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible for garbage collection, when it is no longer used by the active part of the program. Execution of destructor may occur at any time after the instance or object becomes eligible for destruction.

As a complement to what Marc has already mentioned, it should very rarely be necessary to create a finalizer since the introduction of SafeHandle in .NET 2.0. For details, see http://blogs.msdn.com/b/bclteam/archive/2005/03/16/396900.aspx and http://www.bluebytesoftware.com/blog/2005/12/27/NeverWriteAFinalizerAgainWellAlmostNever.aspx .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM