Skip to content

Ownership transfer and ImplicitObjectCreationExpressionSyntax #583

Open
@dlebansais

Description

@dlebansais

Consider the two classes below:

internal sealed class A : IDisposable
{
    private Mutex _mutex = new Mutex();
    private bool _isDisposed;

    private void Dispose(bool disposing)
    {
        if (!_isDisposed)
        {
            if (disposing)
            {
                _mutex?.Dispose();
            }

            _isDisposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(disposing: true);
    }
}

internal sealed class B(A a, bool leaveOpen = false) : IDisposable
{
    private A _a = a;
    private bool _leaveOpen = leaveOpen;
    private bool _isDisposed;

    private void Dispose(bool disposing)
    {
        if (!_isDisposed)
        {
            if (disposing)
            {
                if (!_leaveOpen)
                {
                    _a?.Dispose();
                }
            }

            _isDisposed = true;
        }
    }

    public void Dispose()
    {
        Dispose(disposing: true);
    }
}

This code does not generate any diagnostic, as expected:

IDisposable CreateB()
{
    A a = new();
    B b = new B(a);
    return b;
}

But this one does:

IDisposable CreateB()
{
    A a = new(); // IDISP001: Dispose created
    B b = new(a); // ImplicitObjectCreationExpressionSyntax
    return b;
}

Am I right to think they should behave the same? If so, I think the issue is in Disposable.DisposedByReturnValue.cs line 66, where Parent: ObjectCreationExpressionSyntax should be Parent: BaseObjectCreationExpressionSyntax.

There might be other cases where the replacement of ObjectCreationExpressionSyntax with BaseObjectCreationExpressionSyntax is warranted.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions