Click here to Skip to main content
15,881,413 members
Articles / Programming Languages / C#
Alternative
Tip/Trick

C# equivalent of VB's With keyword

Rate me:
Please Sign up or sign in to vote.
3.00/5 (1 vote)
16 Feb 2012CPOL 10.7K   2
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)


Written By
Brightmoore Solutions LLC
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.
This is a Organisation (No members)


Comments and Discussions

 
GeneralReason for my vote of 3 Why not just use VB? Pin
Michael Kingsford Gray20-Feb-12 19:25
Michael Kingsford Gray20-Feb-12 19:25 
General"This class wraps any Type" -- Unless it doesn't have a para... Pin
PIEBALDconsult16-Feb-12 5:18
mvePIEBALDconsult16-Feb-12 5:18 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.