sealed class CodeX.OwnerAttribute

Derived from

Attribute abstract

The Owner is used on storage containers (i.e. local variables, method/constructor parameters and fields) to declare ownership of disposable objects.

The following rules depict - based on the ownership status - when a disposable object must be disposed and when disposal must not be performed. Going by these rules will avoid situations where a resource is disposed although it is still being used and situations when a resource is never explicitly disposed, thus wasting system resources.

  • When used on a local variable:
    A local variable is considered being attributed iff it is followed by a comment statement and the comment (after eliminating leading and trailing whitespaces) is equal to '[!]':

    IDisposable myObj; // [!]

    The local variable takes ownership of the disposable object that is assigned to it. The code block that declares the local variable is responsible for disposing the object(s) that it stores in the local variable.

  • When used on an instance field:

    IDisposable myObj;

    The declaring class is responsible for disposing the fields value. This implies that the class itself must be disposable (i.e. it must declare a non-static disposal method, see Dispose). The attributed field must be disposed in the classes disposal method.

  • When used on a method/constructor parameter:

    void SomeMethod([Owner] IDisposable myObj) { ... }

    The parameter takes ownership of the disposable object that is passed to it and the method body becomes responsible for disposal.