Members, Constructor and Destructor

Members, Constructor and Destructor

In C#, a constructor is a special method that is automatically called when an instance of a class is created. It is used to initialize the instance variables of the class and prepare the object for use. Constructors have the same name as the class and can be overloaded with different parameter lists to allow for different ways of initializing the object.

Here is an example of a constructor in C#:

csharp

Copy code

publicclassMyClass { publicint myInt; publicstring myString; publicMyClass(int i, string s) { myInt = i; myString = s; } }

In this example, the constructor takes two parameters, an integer and a string, and initializes the myInt and myString instance variables of the MyClass object.

A destructor in C# is a special method that is called when an object is no longer needed and is about to be destroyed by the garbage collector. It is used to perform any necessary cleanup operations on the object, such as releasing resources like file handles or network connections.

Here is an example of a destructor in C#:

csharp

Copy code

publicclassMyClass { publicint myInt; publicstring myString; ~MyClass() { // perform cleanup operations here } }

In this example, the destructor is named ~MyClass and does not take any parameters. It can be used to perform any necessary cleanup operations on the MyClass object before it is destroyed. Note that in C#, destructors are not commonly used, as the garbage collector handles most cleanup operations automatically.

Share this post
[social_warfare]
Installation
Properties and Indexers

Get industry recognized certification – Contact us

keyboard_arrow_up