-2

I am looking on some code and I see:

public class AccountController : Controller
{
   public AccountController()   
          : this(new xxxxxx...

I understand it is a constructor of AccountController, but was is the meaning of ": this"?

Thanks, zalek

Zalek Bloom
  • 551
  • 6
  • 13

4 Answers4

1

:this after a constructor will invoke another overload of the constructor.

Consider this:

public class Offer {
    public string offerTitle { get; set; }
    public string offerDescription { get; set; }
    public string offerLocation { get; set; }

    public Offer():this("title") {

    }

    public Offer(string offerTitle) {
        this.offerTitle = offerTitle;
    }
}

If the caller invokes new Offer(), then, internally it will invoke another constructor which will set the offerTitle to "title".

EngineerSpock
  • 2,575
  • 4
  • 35
  • 57
0

It makes sure an overloaded constructor in the same class is called, e.g.:

class MyClass
{
    public MyClass(object obj) : this()
    {
        Console.WriteLine("world");
    }

    public MyClass()
    {
        Console.WriteLine("Hello");
    }
}

Output when calling the constructor with an argument:

Hello

world

Community
  • 1
  • 1
Emile Pels
  • 3,837
  • 1
  • 15
  • 23
0

:this means that it will call parent's main class constructor (in this case Controller)

0

The this keyword allows you to call one constructor from another constructor in the same class. Let's say you have two constructors in your class, one with parameters and one without parameters. You can use the this keyword on the constructor with no parameter to pass default values to the constructor with parameters, like this:

public class AccountController : Controller
{
   public AccountController() : this(0, "")   
   {
       // some code
   }

   public AccountController(int x, string y)   
   {
       // some code
   }
}

There's also a base keyword that you can use to call a constructor in the base class. The constructor in the following code will call the constructor of the Controller class.

public class AccountController : Controller
{
   public AccountController() : base()   
   {
       // some code
   }
}
ataravati
  • 8,891
  • 9
  • 57
  • 89