Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Object instance valid only for the current method

Tags:

c#

.net

Is it possible to create an object that can register whether the current thread leaves the method where it was created, or to check whether this has happened when a method on the instance gets called?

ScopeValid obj;

void Method1()
{
    obj = new ScopeValid();
    obj.Something();
}

void Method2()
{
    Method1();
    obj.Something(); //Exception
}

Can this technique be accomplished? I would like to develop a mechanism similar to TypedReference and ArgIterator, which can't "escape" the current method. These types are handled specially by the compiler, so I can't mimic this behavior exactly, but I hope it is possible to create at least a similar rule with the same results - disallow accessing the object if it has escaped the method where it was created.

Note that I can't use StackFrame and compare methods, because the object might escape and return to the same method.

like image 937
IS4 Avatar asked Mar 16 '23 06:03

IS4


1 Answers

Changing method behavior based upon the source of the call is a bad design choice.

Some example problems to consider with such a method include:

  • Testability - how would you test such a method?
  • Refactoring the calling code - What if the user of your code just does an end run around your error message that says you can't do that in a different method than it was created? "Okay, fine! I'll just do my bad thing in the same method, says the programmer."

If the user of your code breaks it, and it's their fault, let it break. Better to just document your code with something like:

IInvalidatable - Types which implement this member should be invalidated with Invalidate() when you are done working with this.

Ignoring the obvious point that this almost seems like is re-inventing IDisposible and using { } blocks (which have language support), if the user of your code doesn't use it right, it's not really your concern.


This is likely technically possible with AOP (I'm thinking PostSharp here), but it still depends on the user using your code correctly - they would have to have it in the build process, and failing to function if they aren't using a tool just because you're trying to make it easy on them is evil.

Another point - If you are just attempting to create an object which cannot be used outside of one method, and any attempted operation outside of the method would fail, just declare it a local inside the method.

Related: How to find out which assembly handled the request

like image 163
jdphenix Avatar answered Mar 18 '23 18:03

jdphenix