ChampChris
ChampChris

Reputation: 1631

Constructors that do not duplicate code

I have 2 constructor that have a base call in them as so;

public MyApplication(myEntities context)
            :base(context)
{
    _1stApp = new 1stApplication(this._context);
    _2ndApp = new 2ndApplication(this._context);
    // etc...
}

public MyApplication()
            :base()
{
    _1stApp = new 1stApplication(this._context);
    _2ndApp = new 2ndApplication(this._context);
    // etc...
}

along with the base constructors

public BaseApplication()
{
    _context= new myEntities ();
}

public BaseApplication(myEntities context)
{
    if (context==null)
        _context = context;
    else
        _context= new myEntities ();
}

inside the MyApplication constructors I either want to pass in a context that was created by another application or i want to create a new context. in either case i want to share that same context with all the other application class's (1stApp,2ndApp,etc...) that MyApplication will be instantiating.

i dont want to have to keep same code in both places.

Upvotes: 0

Views: 95

Answers (3)

Thomas Weller
Thomas Weller

Reputation: 11717

You can go with only ONE c'tor (if you're using C# 3.5 or above). Just use an optional argument like this:

public MyApplication(myEntities context = null)
            :base(context)
    {

        _1stApp = new 1stApplication(this._context);
        _2ndApp = new 2ndApplication(this._context);
        etc...
    }

public BaseApplication(myEntities context)
        {
            if (context!=null)
                _context = context;
            else
                _context= new myEntities ();
        }

HTH Thomas

Upvotes: 1

Felipe Oriani
Felipe Oriani

Reputation: 38608

Before the body of the constructor, use either:

For base class constructors use:

 : base (arguments)

For the same class, but another constructor, use:

 : this (arguments)

In your case, this this keywork:

public MyApplication(myEntities context)
        :base(context)
{
    // custom
}

public MyApplication()
     : this (new myEntities())
{
    _1stApp = new 1stApplication(this._context);
    _2ndApp = new 2ndApplication(this._context);
    etc...
}

Upvotes: 0

mp3ferret
mp3ferret

Reputation: 1193

public MyApplication(myEntities context)
        :base(context)
{
   _1stApp = new 1stApplication(this._context);
   _2ndApp = new 2ndApplication(this._context);
   etc...
}

public MyApplication()
    :this(new myEntities())
{ }

Upvotes: 5

Related Questions