| ScopeGuardT Class |  | 
 Inheritance Hierarchy
Inheritance HierarchyNamespace: Lawo
 Syntax
Syntaxpublic sealed class ScopeGuard<T> : IDisposable where T : IDisposable
The ScopeGuardT type exposes the following members.
 Properties
Properties| Name | Description | |
|---|---|---|
|  | Resource | Gets the resource object passed to CreateT(T). | 
 Methods
Methods| Name | Description | |
|---|---|---|
|  | Dismiss | Dismisses the scope guard. Subsequent calls to Dispose will have no effect. | 
|  | Dispose | |
|  | Equals | Determines whether the specified object is equal to the current object.(Inherited from Object.) | 
|  | GetHashCode | Serves as the default hash function. (Inherited from Object.) | 
|  | GetType | Gets the Type of the current instance.(Inherited from Object.) | 
|  | ToString | Returns a string that represents the current object.(Inherited from Object.) | 
 Remarks
RemarksOften, 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
ExamplesStreamWriter 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
Thread Safety See Also
See Also