Differences between constructor and destructor in C #

Source: Internet
Author: User

Put the object initialization work in the constructor, and put the cleanup work in the destructor. When an object is created, the constructor is automatically executed. When an object dies, the Destructor is automatically executed. In this way, you do not have to worry about the initialization and clearing of objects.

Destructor are controlled by the garbage collector.

 

The Destructor is controlled by the garbage collector. the initialization of the object is put in the constructor, And the cleanup is put in the destructor. When an object is created, the constructor is automatically executed. When an object dies, the Destructor is automatically executed. In this way, you do not have to worry about the initialization and clearing of objects. Do not define destructor. If you want to release unmanaged resources, let the class inherit the idisposable interface to implement the dispose mode.

 

The declared objects in using can be released. For more information, see the example.

 

Using System;

Namespace ConsoleApplication7
{
/** // <Summary>
/// Summary of test.
/// </Summary>
Public class Test: IDisposable
{
Public Test (string name)
{
This. name = name;
}

Private string name;

Public string Name
{
Get {return name ;}
Set {name = value ;}
}

Public static void main ()
{
Console. writeline ("programme start! ");

Test test1 = new test ("1 ");
Using (test1)
{
}
Using (Test test2 = new Test ("2"), test3 = new Test ("3 "))
{
Test test4 = new Test ("4 ");
}

Console. WriteLine ("Programme Over! ");
Console. ReadLine ();
}

Idisposable member # region idisposable Member

Public void dispose ()
{
Console. writeline ("{0} releasing resources", name );
}

# Endregion
}

}

This method is feasible.

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.