this Keyword
Each object has a reference“this” which points to itself.<!--[if !supportLists]-->Two uses of this keyword.<!--[endif]-->
<!--[if !supportLists]-->o Can be used to refer to the current object.<!--[endif]-->
<!--[if !supportLists]-->o It can also be used by one constructor to explicitly invoke another constructor of the same class.<!--[endif]-->
Eg1:
class Student
{
private string name;
private int age;
Student(string name, int age)
{
this.name = name;
This.age = age;
}
}
Eg2:
class Circle
{
double x,y,radius;
Circle(double x){
this(x,0,1);
}
Circle(double x, double y){
this(x,y,1);
}
Circle(double x, double y, double radius){
this.x = x;
This.y = y;
this.radius = radius;
}
}
Constructor
·<!--[if !supportLists]--> A constructor is a special method whose task is to initialize the object of its class.<!--[endif]-->
·<!--[if !supportLists]--> It is special because its name is the same as the class name.<!--[endif]-->
·<!--[if !supportLists]--> They do not have return types, not even void and therefore they cannot return values.<!--[endif]-->
·<!--[if !supportLists]--> They cannot be inherited, though a derived class can call the base class constructor.<!--[endif]-->
·<!--[if !supportLists]--> Constructor is invoked whenever an object of its associated class is created.<!--[endif]-->
·Note: There is always atleast one constructor in every class. If you do not write a constructor, C# automatically provides one for you, this is called default constructor. Eg: class A, default constructor is A().
<!--[if !supportLists]--><!--[endif]-->
No comments:
Post a Comment