views:

42

answers:

2

I'm not looking for a way to associate values with a thread using the 'SetData' method.

I need to store some kind of data that will only exist during the scope of a calling method, could be the immediate parent or any other call that is made down on the stack. For example:

void SomeMethod()
{
   string someInfo = "someInfo";
   SomeOtherMethod();   
   object data = GetDataOnCurrentScope("someKey");
}

void SomeOtherMethod()
{
   SetDataOnParentScope("someKey", somevalue);
}

In this case both the 'someInfo' local variable and the data set with the "someKey" key will disapear after 'SomeMethod' returns. Is something like this possible? This may go against the rules of a stack, but who knows if someone has an idea...

obs: Currently, I guess the only way is to have a compiler declare a reference to a dictionary in the beginning of every method's call stack. That dictionary would be eligible for garbage collection when the method returns.

+1  A: 

Personally with the example that you are providing I don't see how this is going to be useful, and from an implementation perspective it will be a royal PITA.

What you are describing here is a function that returns a value, so why not have a return type and use methods in the manner in which they are designed?

Mitchel Sellers
It would be useful in AOP, for example, if 'SomeMethod' asks an object to open a database connection, one could intercept the database opening method and set a transaction associated to the call scope of 'SomeMethod', without having to set pre defined interception points.
Thiado de Arruda
A: 

If you want something scoped from one method to another and nowhere else, you would typically create an object in the first method and pass it as a parameter to the second, or have the second method return the object needed by the first. It depends upon who needs the object first.

Anthony Pegram
read above comment
Thiado de Arruda