constructor and destructor in c# with example
A constructor looks like a special method having no return type and its name is the same as the class name.
If we do not declare a constructor explicitly for a class, the compiler will create a default constructor at run time.
Access modifiers of the constructor can be public, private, protected, internal and extern.
A public constructor is called when the class is instantiated.
A private constructor prevents the creation of the object of the class. It is used in classes having only static members.
A class having an internal constructor cannot be instantiated outside of the assembly.
A protected constructor of a base class can only be called from the derived class within a derived class constructor.
When a constructor having an extern modifier, the constructor is said to be an external constructor, because the same does not provide any actual implementation.
Follow The example constructor and destructor in c# with example.
using System;
class Person {
public string firstName;
public string lastName;
public int age;
public Person() {
Console.WriteLine("Object is being created");
}
~Person() {
Console.WriteLine("Object is being deleted");
}
public string fullName() {
string str = firstName + " " + lastName;
return str;
}
public void setAge(int num) {
age = num;
}
}
class Program {
static void Main(string[] args) {
Person person1 = new Person();
person1.firstName = "Thomas";
person1.lastName = "Gates";
person1.setAge(25);
Console.WriteLine("Full Name : {0}", person1.fullName());
Console.WriteLine("Age : {0}", person1.age);
}
}
No comments:
Post a Comment