-3

Hello am trying to learn C#, I came across this code from a C# tutorial:

Public Class A()
{
    Public A () : this(capacity:10) 
    {
    }

    public int capacity 
    {
        get { return _buffer.length;}
    }
}

I just did not understand why he used : between Public A () and this(capacity:10).

I did not know what to search for on Google so I decided to ask here.

My question is: what is this used for and why?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Skoochapp
  • 31
  • 1
  • 1
  • 6

1 Answers1

0

The code provided doesn't compile. Probably, the code be something like this:

  // lower case for "public" and "class" 
  public class A {
    // _buffer is addressed in "capacity" property, let it be an array 
    private int[] _buffer = new int[10];

    // this constructor is mandatory for the code below
    public A(int capacity) {
    }

    // Now, your question:
    // "this(capacity: 10)" calls the costructor above 
    // "public A(int capacity)"
    // while passing the "capacity" parameter by its name
    public A () : this(capacity: 10)
    {
    }

    public int capacity {
    get {
      return _buffer.Length;
    }
  }

If I guessed right this(capacity: 10) is a call of the constructor public A(int capacity) while passing capacity by name

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215