private static void Main(string[] args)
public static void DoStuff()
var testclass = new TestClass();
Console.WriteLine($"After Do Stuff: {testclass.TestBool}");
public abstract class ScopedObject<T> : IDisposable where T : struct
protected readonly T endValue;
protected readonly object instance;
protected readonly PropertyInfo property;
protected ScopedObject(object instance, PropertyInfo property, T startValue, T endValue)
this.instance = instance;
this.property = property;
this.endValue = endValue;
if (property.PropertyType != typeof(T))
throw new TypeAccessException("Mismatched type of property and scoped object. " +
$"Expected {typeof(T)}, got {property.PropertyType} instead");
property.SetValue(instance, startValue);
property.SetValue(instance, endValue);
public static class ScopedObjectHelpers
public static PropertyInfo GetPropertyInfoFor(this Type declaringType, string propertyName)
return declaringType.GetProperties().First(p => p.Name == propertyName);
public sealed class ScopedBool : ScopedObject<bool>
public ScopedBool(object instance, PropertyInfo property, bool startValue = true, bool endValue = false)
: base(instance, property, startValue, endValue) { }
public bool TestBool { get; set; }
Console.WriteLine($"Start Test bool: {TestBool}");
using var scopedBool = new ScopedBool(this, GetType().GetPropertyInfoFor(nameof(TestBool)));
Console.WriteLine($"End Test bool: {TestBool}");