Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

C# equivalent of VB's With keyword

3.00/5 (1 vote)
16 Feb 2012CPOL 11K  
This class wraps any Type to allow it to be used only within the context of a using statement. It allows for implicit casting to T so it is pretty transpartent.Example usage: using(string scoped_string = Scope(Hello, World!)) { ...
This class wraps any Type to allow it to be used only within the context of a using statement. It allows for implicit casting to T so it is pretty transpartent.

Example usage:
C#
using(string scoped_string = Scope<string>("Hello, World!")) 
{
     Console.WriteLine(scoped_string);
}
</string>


The class:
C#
public sealed class Scope<t>: IDisposable where T: new()
{
    public Scope(T value)
    {
        _Value = value;
    }

    public Scope()
    {
        _Value = new T();
    }

    public static implicit operator T(Scope<t> scope)
    {
        return scope._Value;
    }

    private bool _Disposed = false;
    private T _Value;

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    public void Dispose(bool disposing)
    {
        if (_Disposed) return;           
        _Disposed = true;
    }
}
</t></t>

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)