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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T15:48:16+00:00 2026-05-13T15:48:16+00:00

Consider the following C# code using a COM object. MyComObject o = new MyComObject;

  • 0

Consider the following C# code using a COM object.


MyComObject o = new MyComObject;
try
{
 var baz = o.Foo.Bar.Baz;
 try
 { 
  // do something with baz
 }
 finally
 {
  Marshal.ReleaseComObject(baz);
 }
}
finally
{
 Marshal.ReleaseComObject(o);
}

This will release the COM objects o and baz, but not the temporary objects returnd by o.Foo and o.Foo.Bar.
This can cause problems, when those objects hold a large amount of unmanaged memory or other resources.

An obvious but ugly solution would be, to clutter the code even more with try-finally and Marshal.ReleaseComObject. See
C# + COM Interop, deterministic release

As a workaround, I created a helper class


class TemporaryComObjects: IDisposable
{
 public C T<C>(C comObject)
 {
  m_objects.Add(comObject);
  return comObject;
 }
 public void Dispose()
 {
  foreach (object o in m_objects)
   Marshal.ReleaseComObject(o);
 }
}

Usage:


using (TemporaryComObjects t = new TemporaryComObjects())
{
 MyComObject o = t.T(new MyComObject);
 var baz = t.T(t.T(t.T(o.Foo).Bar).Baz);
 // do something with baz
}

My questions:
Are there potential problems with this code?
Has anybody a more elegant solution?

  • 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-13T15:48:17+00:00Added an answer on May 13, 2026 at 3:48 pm

    My biggest gripe would be the name, T; Add might be more illusrative of the usage. I’d also add where T : class to the generic method, but the “fluent API” seems usable. I’d also be inclined to flatten the code a bit. I can also see some ways of using the Expression API to walk an entire tree and capture all the intermediate steps, but it wouldn’t be trivial – but imagine:

    using(var com = new SomeWrapper()) {
        var baz = com.Add(() => new MyComObject().Foo.Bar.Baz);
    }
    

    where that is an expression tree and we get the intermediaries automatically.

    (also, you could Clear() or null the list in Dispose())


    Like so:

    static class ComExample {
        static void Main()
        {
            using (var wrapper = new ReleaseWrapper())
            {
                var baz = wrapper.Add(
                    () => new Foo().Bar.Baz);
                Console.WriteLine(baz.Name);
            }
        }
    }
    
    class ReleaseWrapper : IDisposable
    {
        List<object> objects = new List<object>();
        public T Add<T>(Expression<Func<T>> func)
        {
            return (T)Walk(func.Body);
        }
        object Walk(Expression expr)
        {
            object obj = WalkImpl(expr);
            if (obj != null && Marshal.IsComObject(obj) && !objects.Contains(obj)) 
            {
                objects.Add(obj);
            }
            return obj;
        }
        object[] Walk(IEnumerable<Expression> args)
        {
            if (args == null) return null;
            return args.Select(arg => Walk(arg)).ToArray();
        }
        object WalkImpl(Expression expr)
        {
            switch (expr.NodeType)
            {
                case ExpressionType.Constant:
                    return ((ConstantExpression)expr).Value;
                case ExpressionType.New:
                    NewExpression ne = (NewExpression)expr;
                    return ne.Constructor.Invoke(Walk(ne.Arguments));
                case ExpressionType.MemberAccess:
                    MemberExpression me = (MemberExpression)expr;
                    object target = Walk(me.Expression);
                    switch (me.Member.MemberType)
                    {
                        case MemberTypes.Field:
                            return ((FieldInfo)me.Member).GetValue(target);
                        case MemberTypes.Property:
                            return ((PropertyInfo)me.Member).GetValue(target, null);
                        default:
                            throw new NotSupportedException();
    
                    }
                case ExpressionType.Call:
                    MethodCallExpression mce = (MethodCallExpression)expr;
                    return mce.Method.Invoke(Walk(mce.Object), Walk(mce.Arguments));
                default:
                    throw new NotSupportedException();
            }
        }
        public void Dispose()
        {
            foreach(object obj in objects) {
                Marshal.ReleaseComObject(obj);
                Debug.WriteLine("Released: " + obj);
            }
            objects.Clear();
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 300k
  • Answers 300k
  • 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 I think you could do this using spring's org.springframework.core.io.support.PathMatchingResourcePatternResolver. At… May 13, 2026 at 7:57 pm
  • Editorial Team
    Editorial Team added an answer I had the exact problem and it was solved easily.… May 13, 2026 at 7:57 pm
  • Editorial Team
    Editorial Team added an answer A UUID is a Universally Unique ID. It's the universally… May 13, 2026 at 7:57 pm

Related Questions

I was of the opinion that virtualization doesnt work in the super class constructor
While answering a question on SO yesterday, I noticed that if an object is
Update: See the bottom of this question for a C# workaround. Hi there, Consider
We are in evaluating technologies that we'll use to store data that we gather
Consider this code for loading, modifying and saving a Bitmap image: using (Bitmap bmp

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.