Search code examples
c#scopeusing

Is it possible to detect the variable of a using from another function and access that variable?


I have a function which calls another function. I want to know if within that second function I can detect if it is being invoked from the first function within a using-scope. If I can detect it, I want to access the variable inside that using-scope. I cannot send the variable through a parameter.

For example:

// Normal call to OtherFunction
void function1()
{
    SomeClass.OtherFunction();
}


// Calling using someVar
void function2()
{
    using(var someVar = new someVar())
    {
        SomeClass.OtherFunction();
    }
}

// Calling using other variable, in this case, similar behaviour to function1()
void function3()
{
    using(var anotherVar = new anotherVar())
    {
        SomeClass.OtherFunction();
    }
}

class SomeClass
{
    static void OtherFunction()
    {
         // how to know if i am being called inside a using(someVar)
         // and access local variables from someVar
    }
}

Solution

  • You could use the same mechanisme as System.Transaction.TransasctionScope. This only works if all context's can have the same base class. The base class registerers himself in a static property during construction and removes himself at dispose. If another Context is already active, it is surpressed until the newest Context is disposed again.

    using System;
    
    namespace ContextDemo
    {
        class Program
        {
            static void Main(string[] args)
            {
                DetectContext();
                using (new ContextA())
                    DetectContext();
                using (new ContextB())
                    DetectContext();
            }
    
            static void DetectContext()
            {
                Context context = Context.Current;
                if (context == null)
                    Console.WriteLine("No context");
                else 
                    Console.WriteLine("Context of type: " + context.GetType());
            }
        }
    
        public class Context: IDisposable
        {
            #region Static members
    
            [ThreadStatic]
            static private Context _Current;
    
            static public Context Current
            {
                get
                {
                    return _Current;
                }
            }
    
            #endregion
    
            private readonly Context _Previous;
    
            public Context()
            {
                _Previous = _Current;
                _Current = this;
            }
    
            public void Dispose()
            {
                _Current = _Previous;
            }
        }
    
        public class ContextA: Context
        {
        }
    
        public class ContextB : Context
        {
        }
    }