Click or drag to resize
ScopeGuardT Class
Simplifies resource object handling in functions that only create resource objects (but do not dispose them).
Inheritance Hierarchy
SystemObject
  LawoScopeGuardT

Namespace: Lawo
Assembly: Lawo (in Lawo.dll) Version: 1.4.1707.27006
Syntax
C#
public sealed class ScopeGuard<T> : IDisposable
where T : IDisposable

Type Parameters

T
The type of the resource object.

The ScopeGuardT type exposes the following members.

Properties
Methods
  NameDescription
Public methodDismiss
Dismisses the scope guard. Subsequent calls to Dispose will have no effect.
Public methodDispose
Public methodEquals
Determines whether the specified object is equal to the current object.
(Inherited from Object.)
Public methodGetHashCode
Serves as the default hash function.
(Inherited from Object.)
Public methodGetType
Gets the Type of the current instance.
(Inherited from Object.)
Public methodToString
Returns a string that represents the current object.
(Inherited from Object.)
Top
Remarks

Often, a function needs to do other stuff besides constructing the resource object (e.g. creating child resource objects that the main resource will own or setting some properties after creation). In .NET pretty much any of these operations can fail by throwing an exception. Without the help of this class, one try-catch block would be necessary for the creation of each of these resource objects. In the try block the resource is created and possibly initialized, in the catch block the resource is disposed and the exception rethrown.

This class is an adapted version of the facility presented in this article.

Examples
StreamWriter CreateWriter()
{
    using (ScopeGuard<FileStream> streamGuard =
        ScopeGuard.Create(new FileStream("C:\test.txt", FileMode.CreateNew)))
    using (ScopeGuard<StreamWriter> writerGuard =
        // At this point, the FileStream object is automatically disposed if the StreamWriter constructor throws
        ScopeGuard.Create(new StreamWriter(streamGuard.Resource)))
    {
        // Here both resource objects are automatically disposed if the following statement throws
        writerGuard.Resource.AutoFlush = true;
        writerGuard.Dismiss(); // The whole creation succeeded -> dismiss both guards
        streamGuard.Dismiss();
        return writerGuard.Resource;
    }
}
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.
See Also