tags:

views:

136

answers:

2

This is related to my other question, but this time very specific. Is it possible, using AOP (PostSharp in particular) to detect if function's return value was used? For example

var x = y.func();  // used
y.func(); // not used

Note that detection should be performed for this particular call, not for the function in general.

I never used AOP/PostSharp so even if I don't find answer in PostSharp's docs I can't be sure it's not there. I do not insist on PostSharp, though; I'm OK to use any library as long as it can do the job.

A: 

While it's very likely possible, it's very much the wrong tool for the job, so you would end up doing more work than necessary to implement a solution. I would recommend that you return to your other question and focus on finding a better candidate approach instead of focusing on how you might sink a nail with a screwdriver...

Nicole Calinoiu
+1  A: 

You can't use AOP for that, but it's quite easy (when you know the tool) to write some MSIL analysis that does the job.

Basically, when a method return value is not used, there is a 'pop' instruction just after the 'call' or 'callvirt'. You could do PostSharp to do the job (use the low-level weaver, define an IAdvice intercepting calls of the method you want, define an InstructionSequence bookmark, read one more instruction, test if it is 'pop', and rollback to the bookmark so that the scan can continue safely.

But I wonder why you would need that and I agree with Nicole's answer.

Gael Fraiteur
Even though I'm going to agree with Nicole and use FxCop for this, your answer does answer the question and is actually very useful. PostSharp really seems to be useful and powerful!
queen3