Click here to Skip to main content
12,629,107 members (35,583 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

5.5K views
Posted

C# equivalent of VB's With keyword

, 16 Feb 2012 CPOL
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>

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)



You may also be interested in...

Comments and Discussions

 
GeneralReason for my vote of 3 Why not just use VB? Pin
Michael K Gray20-Feb-12 20:25
memberMichael K Gray20-Feb-12 20:25 
General"This class wraps any Type" -- Unless it doesn't have a para... Pin
PIEBALDconsult16-Feb-12 6:18
memberPIEBALDconsult16-Feb-12 6: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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.161205.3 | Last Updated 16 Feb 2012
Article Copyright 2012 by Brightmoore Solutions LLC
Everything else Copyright © CodeProject, 1999-2016
Layout: fixed | fluid