Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I combine constructors in C#

Tags:

c#

I have the following code:

    public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
    {
        this._modelState = modelStateDictionary;
        this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
        this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
    }

    public AccountService(string dataSourceID)
    {
        this._accountRepository = StorageHelper.GetTable<Account>(dataSourceID);
        this._productRepository = StorageHelper.GetTable<Product>(dataSourceID);
    }

Is there some way that I can simplify the constructors so each doesn't have to do the StorageHelper calls?

Also do I need to specify this. ?

like image 976
Samantha J T Star Avatar asked Dec 11 '11 03:12

Samantha J T Star


1 Answers

public AccountService(ModelStateDictionary modelStateDictionary, string dataSourceID)
    : this(dataSourceID)
{
    this._modelState = modelStateDictionary;

}

This will first call your other constructor. You can also use base(... to call a base constructor.

this in this case is implied.

like image 196
Yuriy Faktorovich Avatar answered Oct 06 '22 17:10

Yuriy Faktorovich