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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T06:20:01+00:00 2026-05-13T06:20:01+00:00

Edit: Two options shown below. If you’re just using the functionality that an IDisposable

  • 0

Edit: Two options shown below.

If you’re just using the functionality that an IDisposable provides, the aptly named using clause works fine. If you’re wrapping an IDisposable in an object, the containing object itself needs to be IDisposable and you need to implement the appropriate pattern (either a sealed IDisposable class, or the messier but standard virtual pattern).

But sometimes a helper factory method is good for cleanliness. If you return an IDisposable directly after construction, you’re fine, but if you first construct it and then modify it or otherwise execute code that can throw an exception before returning, you need to safely call .Dispose() – but only if there was an error.

For example, unsafe code could look like this…

DbCommand CreateCommandUnsafely(string commandText)
{
    var newCommand = connection.CreateCommand();
    newCommand.CommandText = commandText;  //what if this throws?
    return newCommand;
}    

Solutions Two safe variants follows…

DbCommand CreateCommandSafelyA(string commandText)
{
    DbCommand newCommand = null;
    bool success = false;
    try    {
        newCommand = connection.CreateCommand();
        newCommand.CommandText = commandText; //if this throws...
        success=true;
        return newCommand;
    } finally{
        if (!success && newCommand != null )
            newCommand.Dispose(); //...we'll clean up here.
    }
}


DbCommand CreateCommandSafelyB(string commandText)
{
    DbCommand newCommand = null;
    try    {
        newCommand = connection.CreateCommand();
        newCommand.CommandText = commandText; //if this throws...
        return newCommand;
    } catch {
        if (newCommand != null)
            newCommand.Dispose(); //...we'll clean up here.
        throw;
    }
}

Safe variant A is just one line longer, but seems to be the idiomatic approach. There don’t seem to be any really concise solutions, although some posters below give some lambda-using options that extract the encapsulate this logic.

The code bloat with any of the above safe methods remains, and is particularly aggravating with code that originally looked like…

return new MyDisposableThing {
    OptionA = "X",
    OptionB = B.Blabla,
    Values = src.Values.Where(priority => priority > 1.0),
};

The above code gets written safely is quite a bit longer and less readable because you can no longer safely use the shortened setter syntax.

  • 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-13T06:20:02+00:00Added an answer on May 13, 2026 at 6:20 am

    I believe this is the standard pattern:

    DbCommand CreateCommand(string commandText)
    {
        DbCommand newCommand = null;
        bool success = false;
        try
        {
            newCommand = connection.CreateCommand();
            newCommand.CommandText = commandText;
            success = true;
            return newCommand;
        }
        finally
        {
            if (!success & newCommand != null)
                newCommand.Dispose();
         }
    }
    

    It does not catch and rethrow the error.

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

Sidebar

Ask A Question

Stats

  • Questions 320k
  • Answers 320k
  • 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 That's not a function, that's a local variable created by… May 14, 2026 at 12:19 am
  • Editorial Team
    Editorial Team added an answer To generate 1 random vector with elements from {0, 1}:… May 14, 2026 at 12:19 am
  • Editorial Team
    Editorial Team added an answer You can store target_view.frame in an instance variable when touchBegan… May 14, 2026 at 12:19 am

Related Questions

Since all files in a web project are compiled into single assembly, then does
I have a question with fluent interfaces. We have some objects that are used
I am using ASP.Net MVC along with Jquery to create a page which contains
I've got a DataGridView in a modal window with a list of options for
I'm a bit newbieish when it comes to the deeper parts of OSX configuration

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.