Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 3406240
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 18, 20262026-05-18T05:36:13+00:00 2026-05-18T05:36:13+00:00

Is there an accepted method of adding possibly-derived objects to a collection without allowing

  • 0

Is there an accepted method of adding possibly-derived objects to a collection without allowing instances of the base or derived objects to be created on their own? I’m thinking that’s almost a contradiction in terms.

About the only method I’ve been able to come up with is to add to the parent collection from the child’s base implementation like this:

// Child constructors
private void Child() { }
protected void Child(Parent parent)
{
    parent.Collection.Add(this);
}

This forces the child object to always be instantiated with a parent, but it seems like a rather messy implementation to add a child class to a parent collection from the child. I know I can pass a Type-type variable to a method, and this might be the way to go, but I’m not sure how to create/cast to the passed type.


Update: I’m playing around with code that looks like this as a possible generic ChildCollection.Add method, in case this gives anybody a better picture of what I want…we’ll see if it works in the long run:

// Currently testing directly in Parent class;
// can later be moved/modified for Parent's ChildCollection class.
public Child AddTest(string info, Type derivedType)
{
    ConstructorInfo ci = derivedType.GetConstructor(new Type[] { typeof(Parent) });
    Child myBaby = (Child) ci.Invoke(new Object[] { this });
    myBaby.Initialize(info);
    return myBaby;
}

This could then be called with code like:

Child newChild = Parent.AddTest("Hello World", typeof(DerivedChild));
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-18T05:36:14+00:00Added an answer on May 18, 2026 at 5:36 am

    Ultimately, I’ve gone for code very similar to what I posted in my update. I’m posting it here, as I think it’s a useful technique for either a generic object factory or a limited one (in this case, limited to those that derive from the Child class).

    The basic idea is to create a custom collection, then use an Add method (or perhaps I should name it Create?) to instantiate the object and properly handle any overridden initialization in a Child derivative.

    Here’s a skeleton of the code I ended up with:

    // Use standard Child
    public Child Add(string initInfo)
    {
        Child newChild = new Child(this.Parent);
        // There's actually a bit more coding before Initialize()
        // in the real thing, but nothing relevant to the example.
        newChild.Initialize(initInfo);
        List.Add(newChild);
        return newChild;
    }
    
    // Overload for derived Child.
    public Child Add(Type childDerivative, string initInfo)
    {
        if (!childDerivative.IsSubclassOf(typeof(Child)))
            throw new ArgumentException("Not a subclass of Child.");
        ConstructorInfo ci = childDerivative.GetConstructor(
            BindingFlags.Instance |
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.FlattenHierarchy |
            BindingFlags.ExactBinding, 
            null, new Type[] { typeof(Parent) }, null);
        if (ci == null)
            throw new InvalidOperationException("Failed to find proper constructor.");
        newChild = (Child)ci.Invoke(new Object[] { this.Parent });
        newChild.Initialize(initInfo);
        List.Add(newChild);
        return newChild;
    }
    

    Since this may not cover every possible derived Child the client application might want to create (particularly if they’re adding their own parameters to the constructor), I’m thinking I’ll probably also provide an Add(Child child) method, with the caveat that if the user is instantiating the Child object with a standard “new Child(Parent)”, they’re also responsible for taking all the standard initialization steps in the expected manner.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I know how I use these terms, but I'm wondering if there are accepted
Is there a widely accepted class for dealing with URLs in PHP? Things like:
There doesn't seem to be an accepted way of sending down a header parameter
Is there a way to convert from System.Windows.Forms.HtmlElement to mshtml.IHTMLElemenet3? --edit after answer accepted
I just read this question and the accepted answer: What is JavaScript garbage collection?
Is there a way to test if a collection is already initialized? try-catch only?
Wondering if there's any accepted practice for approximating C++'s 'const methods' in Objective-C. (new
There is a conversion process that is needed when migrating Visual Studio 2005 web
There are two weird operators in C#: the true operator the false operator If
There are two popular closure styles in javascript. The first I call anonymous constructor

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.