Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the function of the "this" keyword in a constructor?

I was looking at sample code from MSDN just now and came accross:

namespace IListSourceCS
{
    public class Employee : BusinessObjectBase
    {
        private string      _id;
        private string      _name;
        private Decimal     parkingId;

        public Employee() : this(string.Empty, 0) {} // <<--- WHAT IS THIS???
        public Employee(string name) : this(name, 0) {}
like image 777
Aaron Anodide Avatar asked Apr 13 '11 02:04

Aaron Anodide


People also ask

What is this in constructor function?

In JavaScript, when this keyword is used in a constructor function, this refers to the object when the object is created.

What is this keyword in constructor?

The this keyword refers to the current object in a method or constructor. The most common use of the this keyword is to eliminate the confusion between class attributes and parameters with the same name (because a class attribute is shadowed by a method or constructor parameter).

Can we use this keyword in constructor?

The “this ” keyword in Java is used as a reference to the current object, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

What is this () in Java?

The this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.


2 Answers

It calls the other constructor in that class with that signature. Its a way of implementing the constructor in terms of other constructors. base can also be used to call the base class constructor. You have to have a constructor of the signature that matches this for it to work.

like image 134
Craig Suchanec Avatar answered Oct 18 '22 13:10

Craig Suchanec


this lets you call another constructor of Employee (current) class with (string, int) parameters.

This is a technique to initialize an object known as Constructor Chaining

like image 43
Sanjeevakumar Hiremath Avatar answered Oct 18 '22 13:10

Sanjeevakumar Hiremath