Constructor, Destructor & Gerbage Collection
Constructor:
- Constructors are class methods that are executed when an object of a Class or Struct is created.
- They have the same name as the class or struct, and usually initialize the data members of the new object.
- A class or struct may have multiple constructors that take different arguments.
- Constructors enable the programmer to set default values, limit instantiation and write code that is flexible and easy to read.
- If you do not provide a constructor for your object, C# will create one by default that instantiates the object and sets member variables to the default values .
- Static classes and structs can also have constructors.
Constructor-example:
public class Time
{
int Year;
int Month;
int Date;
int Hour;
int Minute;
int Second;
public void DisplayCurrentTime( )
{
Console.WriteLine("{0}/{1}/{2} {3}:{4}:{5}“, Month, Date, Year, Hour, Minute, Second);
}
Gerbage Collectin(GC):
GC frees up memory used by those objects which can no longer be accessed by your runtime code.