BADF00D / DisposableFixer

This is a Visual Studio Extension and NuGet package that should identify and fix problems as memleaks while using IDisposables.
Other
35 stars 7 forks source link

Fix "Dispose in Dispose Method" yield in compilation error #94

Closed BADF00D closed 5 years ago

BADF00D commented 5 years ago

Prerequisites

Description

When using CodeFix that disposes a member in Dispose method, a compilation error is introduced into the code. The Problem is that the implementation of the member is IDisposable, but the interface the member has does not.

Source Code

"Source" Soucecode

using System;

namespace SelectManyTest
{
    internal class DisposeInDisposeMethod : IDisposable
    {
        private readonly ISomeInterface _sameInstance;

        public DisposeInDisposeMethod()
        {
            _sameInstance = new SomeImplementation();//not disposed
        }

        public void Dispose()
        {
        }
    }

    public interface ISomeInterface
    {
    }

    public class SomeImplementation : ISomeInterface, IDisposable
    {
        public void Dispose()
        {
        }
    }
}

Becomes:

using System;

namespace SelectManyTest
{
    internal class DisposeInDisposeMethod : IDisposable
    {
        private readonly ISomeInterface _sameInstance;

        public DisposeInDisposeMethod()
        {
            _sameInstance = new SomeImplementation();
        }

        public void Dispose() {
            _sameInstance?.Dispose();//compilation error
        }
    }

    public interface ISomeInterface
    {
    }

    public class SomeImplementation : ISomeInterface, IDisposable
    {
        public void Dispose()
        {
        }
    }
}

But should become:

using System;

namespace SelectManyTest
{
    internal class DisposeInDisposeMethod : IDisposable
    {
        private readonly ISomeInterface _sameInstance;

        public DisposeInDisposeMethod()
        {
            _sameInstance = new SomeImplementation();
        }

        public void Dispose() {
            (_sameInstance as IDisposable)?.Dispose();
        }
    }

    public interface ISomeInterface
    {
    }

    public class SomeImplementation : ISomeInterface, IDisposable
    {
        public void Dispose()
        {
        }
    }
}

Screenshot

2018-11-02_10-54-04

BADF00D commented 5 years ago

Fixed in release 1.1.3