0

Suppose I have a list of COM objects as a property in a class :

public List<LegacyCOMObjects> LegacyCOMObjects { get; set; }

What is the best way to set this property with a new value? Should I do it the classic .NET way or should I release the objects before setting it because memory leaks may happen? I was think of something like this :

private List<LegacyCOMObjects> _legacyCOMObjects ;

public List<LegacyCOMObjects> LegacyCOMObjects 
    {
        get { return _legacyCOMObjects; }
        set 
            { 
                if (_legacyCOMObjects!= null)
                {
                    _legacyCOMObjects.ForEach(o =>
                    {
                        Marshal.ReleaseComObject(o);
                        o = null;
                    });
                }
                _legacyCOMObjects= value; 
            }
    }
Keysharpener
  • 466
  • 3
  • 14
  • 1
    Manual memory management is never a good idea. The garbage collector is quite capable of releasing those COM objects all by itself, it doesn't need help. Don't solve a problem until you have one. – Hans Passant Nov 19 '14 at 14:38
  • From what I've seen, it is generally advised to release com objects once they are no longer used (ex: Excel interop). Do you advise the contrary? – Keysharpener Nov 19 '14 at 14:46
  • 1
    I most certainly do, it is very nasty cargo cult. Read more about it in [this post](http://stackoverflow.com/a/25135685/17034). – Hans Passant Nov 19 '14 at 14:49
  • Very good post, thanks for the heads up. It is strange that your / this point of view is not more visible on the Internet. – Keysharpener Nov 19 '14 at 15:14
  • Future visitors : see this post also : http://stackoverflow.com/questions/17130382/understanding-garbage-collection-in-net/17131389#17131389 – Keysharpener Nov 20 '14 at 08:56

0 Answers0