Click here to Skip to main content
Click here to Skip to main content
Alternative Tip

Tagged as

Go to top

C# equivalent of VB's With keyword

, 16 Feb 2012
Rate this:
Please Sign up or sign in to vote.
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:
using(string scoped_string = Scope<string>("Hello, World!")) 
{
     Console.WriteLine(scoped_string);
}
</string>

 
The class:
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)

Share

About the Author

Brightmoore Solutions LLC
Brightmoore Solutions LLC
United States United States
No Biography provided
Group type: Organisation (No members)



Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web01 | 2.8.140921.1 | Last Updated 16 Feb 2012
Article Copyright 2012 by Brightmoore Solutions LLC
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid