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 792629
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 14, 20262026-05-14T22:01:21+00:00 2026-05-14T22:01:21+00:00

I have a Visual Studio 2008 C# .NET 2.0CF application. I’m using a component

  • 0

I have a Visual Studio 2008 C# .NET 2.0CF application. I’m using a component base from which two concrete components are derived. The application first attempts to use SomeDisposableComponent. Its constructor throws an exception because it requires a feature that isn’t available. Then, the application tries SomeOtherDisposableComponent. Its construction succeeds.

The problem is that the first component’s constructor already added itself to the form’s container of components before the exception was thrown. So, when the form is disposed the first component’s Dispose() member is called even though the object was never fully constructed. That causes problems for the second component’s destructor.

How can I ensure that when the first component throws an exception on construction, the references to it are removed?

public abstract class SomeDisposableComponentBase : Component
{
    private System.ComponentModel.IContainer components;

    private SomeInternalDisposable s_ = new SomeInternalDisposable();

    protected SomeDisposableComponentBase()
    {
        Initializecomponent();
    }

    protected SomeDisposableComponentBase(IContainer container)
    {
        container.Add(this);
        Initializecomponent();
    }

    private void InitializeComponent()
    {
        components = new System.ComponentModel.Container();
    }

    protected abstract void Foo();

    #region IDisposable Members
    bool disposed_;

    protected override void Dispose(bool disposing)
    {
        // called twice. the first time for the component that failed to initialize properly.
        // the second for the one that was used.
        if (!disposed_)
        {
            if (disposing && (components != null))
            {
                components.Dispose();
            }

            // on the second call, this throws an exception because it is already disposed.
            s_.Close();
            disposed_ = true;
        }
        base.Dispose(disposing);
    }
    #endregion    
}

public SomeDisposableComponent : SomeDisposableComponentBase
{
    public SomeDisposableComponent() : base()
    {
    }

    public SomeDisposableComponent(IContainer container) : base(container)
    {
        // This will throw an exception if it requires a feature that isn't available.
        SomeInitFunction();
    }

    protected override void Foo()
    {
        // Do something...
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

public partial class my_form : Form
{
    private SomeDisposableComponentBase d_;

    public my_form()
    {
        InitializeComponent();
        if (null == components)
            components = new System.ComponentModel.Container();

        try
        {
            // try the default component
            d_ = new SomeDisposableComponent(components);
        }
        catch (System.Exception)
        {
            try
            {
                // the default component requires some feature that isn't available. Try a
                // backup component.
                d_ = new SomeOtherDisposableComponent(components);
            }
            catch (System.Exception e)
            {
                // display error to the user if no suitable component can be found.
            }
        }
    }

    /// exit button clicked
    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    /// from the my_form.designer.cs
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            // this function is executed as expected when the form is closed
            components.Dispose();
        }
        base.Dispose(disposing);
    }
}

Thanks,
PaulH


Edit: Removed unused code

The container within the SomeDisposableComponentBase was confusing. It’s not relevant to the issue and I should have removed it earlier.

public abstract class SomeDisposableComponentBase : Component
{       
    private SomeInternalDisposable s_ = new SomeInternalDisposable();

    protected SomeDisposableComponentBase()
    {
    }

    protected SomeDisposableComponentBase(IContainer container)
    {
        container.Add(this);
    }

    protected abstract void Foo();

    #region IDisposable Members
    bool disposed_;

    protected override void Dispose(bool disposing)
    {
        // called twice. the first time for the component that failed to initialize properly.
        // the second for the one that was used.
        if (!disposed_)
        {
            if (disposing)
            {
                // on the second call, this throws an exception because it is already disposed.
                s_.Close();
            }
            disposed_ = true;
        }
        base.Dispose(disposing);
    }
    #endregion    
}

public SomeDisposableComponent : SomeDisposableComponentBase
{
    public SomeDisposableComponent() : base()
    {
    }

    public SomeDisposableComponent(IContainer container) : base(container)
    {
        // This will throw an exception if it requires a feature that isn't available.
        SomeInitFunction();
    }

    protected override void Foo()
    {
        // Do something...
    }

    protected override void Dispose(bool disposing)
    {
        base.Dispose(disposing);
    }
}

public partial class my_form : Form
{
    private SomeDisposableComponentBase d_;

    public my_form()
    {
        InitializeComponent();
        if (null == components)
            components = new System.ComponentModel.Container();

        try
        {
            // try the default component
            d_ = new SomeDisposableComponent(components);
        }
        catch (System.Exception)
        {
            try
            {
                // the default component requires some feature that isn't available. Try a
                // backup component.
                d_ = new SomeOtherDisposableComponent(components);
            }
            catch (System.Exception e)
            {
                // display error to the user if no suitable component can be found.
            }
        }
    }

    /// exit button clicked
    private void Exit_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    /// from the my_form.designer.cs
    protected override void Dispose(bool disposing)
    {
        if (disposing && (components != null))
        {
            // this function is executed as expected when the form is closed
            components.Dispose();
        }
        base.Dispose(disposing);
    }
}
  • 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-14T22:01:21+00:00Added an answer on May 14, 2026 at 10:01 pm

    Your form should be in charge of adding items to its components collection – not the components you’re adding to the collection. Doing it inside the added components makes it extremely difficult to reason about what’s happening in your form.

    // It is not obvious that the component is adding itself to the list
    new SomeDisposableComponent(components);
    
    // Instead, be explicit where it matters
    Component someDisposableComponent = new SomeDisposableComponent(components);
    this.components.Add(someDisposableComponent);
    

    Next, to solve your constructor problem, you should move the logic out of the constructor. This is generally good practice – people do not expect constructors to have side effects, and logic in your constructors makes classes difficult to test. If you want to guarantee that something happens every time you create an instance, create a factory and make it so the factory is the only way to get an instance of your class (make the class’ constructor internal, or use some other technique):

    public class SomeDisposableComponentFactory {
        public SomeDisposableComponent CreateInstance() {
            SomeDisposableComponent component = new SomeDisposableComponent();
            component.SomeInitFunction();
        }
    }
    

    Finally, you should consider moving the logic for selecting and creating components out of your form and into a general component factory:

    public class ComponentFactory {
    
        // The input parameter can be whatever you need to choose the right component
        public Component CreateInstance(object input) {
    
            if (input == something) {
                SomeDisposableComponent component = new SomeDisposableComponent();
                component.SomeInitFunction();
                return component;
            }
            else {
                return new AnotherComponent();
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 411k
  • Answers 411k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer You should be setting the ContextMenuService.Placement attached property on the… May 15, 2026 at 7:50 am
  • Editorial Team
    Editorial Team added an answer The average response time and average turnaround time depends on… May 15, 2026 at 7:50 am
  • Editorial Team
    Editorial Team added an answer As far as I know without Version Control there is… May 15, 2026 at 7:50 am

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

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.