Search code examples
c#constructorthisunirx

the "This" keyword front of constructor parentheses - C#


I know about "This" keyword and what is it working. but what is this using for?

public ReactiveProperty() : this(default(T))
{

}

I have seen this in UniRx Project. I just don't know the "This" keyword front of constructor. I googled it but there is nothing to catch. does anyone know?


Solution

  • This syntax is used to call another constructor defined in the class. Example from the docs:

    class Coords
    {
        public Coords() : this(0, 0) // calls Coords(int x, int y) with x = 0 and y = 0
        {  }
    
        public Coords(int x, int y)
        {
            X = x;
            Y = y;
        }
    
        public int X { get; set; }
        public int Y { get; set; }
    
        public override string ToString() => $"({X},{Y})";
    }
    
    var p1 = new Coords();
    Console.WriteLine($"Coords #1 at {p1}");
    // Output: Coords #1 at (0,0)
    
    var p2 = new Coords(5, 3);
    Console.WriteLine($"Coords #2 at {p2}");
    // Output: Coords #2 at (5,3)