Scoped Values
Here's an interesting utility class, a scoped value. This allows you to have a member variable that gets changed for a time, and then automatically restored back to the original value.
Looked at another way, a Scoped
When is this useful?
One sample use is for the mouse cursor - with a suitably configured Scoped
using (screenCursor.As(Cursors.HourGlass)) { // Long running action }
Contrast this with the code often written for this situation:
Control.Cursor = Cursors.HourGlass; try { // Long running action } finally { Control.Cursor = Cursors.Default; }
One major issue with this code is that it doesn't support nesting - when this particular block completes, the cursor is restored to its default value, even if this block has been called as a part of processing a larger piece of work. Of course, this can be easily addressed by caching the existing value in a temporary variable, but this increases the amount of boilerplate code required.
Using a Scoped
Setup is relatively straightforward, just create a Scoped
Here's a full example ...
public class ExampleForm : Form { public ExampleForm() { mScreenCursor = new Scoped<Cursor>(Cursors.Default); mScreenCursor.ValueChanged += UpdateCursor; } private void UpdateCursor( object sender, ValueChangedEventArgs<Cursor> args) { Cursor = args.Value; } private readonly Scoped<Cursor> mScreenCursor; }
| Attachment | Size |
|---|---|
| Scoped<T> Source | 30.48 KB |

Recent comments
4 weeks 15 hours ago
4 weeks 21 hours ago
4 weeks 1 day ago
4 weeks 1 day ago
8 weeks 1 day ago
9 weeks 16 hours ago
9 weeks 4 days ago
9 weeks 4 days ago
11 weeks 5 days ago
12 weeks 3 hours ago