4

I came across this bit of c# at this link

I cant figure out this line ...

public StockTickerHub() : this(StockTicker.Instance) { }

It looked a bit like inheriting from a base class but I havent seen this used like this before.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace SignalR.StockTicker
{
    [HubName("stockTickerMini")]
    public class StockTickerHub : Hub
    {
        private readonly StockTicker _stockTicker;

        public StockTickerHub() : this(StockTicker.Instance) { }

        public StockTickerHub(StockTicker stockTicker)
        {
            _stockTicker = stockTicker;
        }

        public IEnumerable<Stock> GetAllStocks()
        {
            return _stockTicker.GetAllStocks();
        }
    }
}
Imad Alazani
  • 6,688
  • 7
  • 36
  • 58
spiderplant0
  • 3,872
  • 12
  • 52
  • 91
  • 3
    @dasblinkenlight Unrelated question. He asked about `: this` in constructors, not the general use of `this.stuff`. – Artless Aug 11 '13 at 12:49
  • @Trickery See usage #6 of the accepted answer to that very much related question – Sergey Kalinichenko Aug 11 '13 at 13:03
  • 2
    Disagree, not a duplicate. Doesn't matter if an accepted answer of a different question, answers this question. Can't expect a user to relate the two. – Phill Aug 11 '13 at 13:09

3 Answers3

8

It calls another constructor of the same class.

public class Foo
{
    public Foo() : this (1) { }

    public Foo(int num) 
    {

    }
}

Calling new Foo() will invoke Foo(1).

More info: http://www.dotnetperls.com/this-constructor

Artless
  • 4,522
  • 1
  • 25
  • 40
  • It should be noted that this a special case that only works for constructors. You can't do this with normal methods. – sharoz Aug 11 '13 at 12:44
  • @Trickery : +1 May I please know, What should be the advantage of writing a hard code value in Cross Calling Constructor ? – Imad Alazani Aug 11 '13 at 14:01
  • Lets say you have some initialization code in your default constructor, and you also have constructors with parameters but you still want to call the common initialization you have in the default ctor. – Artless Aug 11 '13 at 14:25
2

this(StockTicker.Instance) fires another class constructor:

Using Constructors (C# Programming Guide):

A constructor can invoke another constructor in the same object by using the this keyword. Like base, this can be used with or without parameters, and any parameters in the constructor are available as parameters to this, or as part of an expression.

MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
0

It calls the another constructor

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331