Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid or detect implicit delegate inference in C#?

I am writing a game using C# and have found a number of cases where a function takes a delegate and I have inadvertently passed in a function name instead of creating and caching a delegate to use as the parameter instead. This causes a delegate object to be created for each call to these functions, which then immediately becomes garbage when the function returns.

I'd like to find all the places where I've made this mistake, and I'd prefer to avoid reading every line of every file looking for them (there are years worth of code). I saw how VB has an 'option strict' which will disable implicit construction of objects which I think would work for me if C# had that feature, but I don't think it does. I've also reviewed compiler warning options and none of them seem to help here either.

Is there any reasonably convenient way to identify these objects created by implicit delegate inference so I can find out where I need to create/cache the callbacks to avoid the garbage?

like image 938
Eric Cosky Avatar asked Apr 25 '12 18:04

Eric Cosky


1 Answers

In short, your question is "how can I find all method group conversions?"

We are at present working on a project code-named Roslyn which will allow you to use the same semantic analysis engine that the C# compiler and IDE uses. It will expose the syntactic model of the language, and then provide a semantic analysis API by which you can ask questions of the semantic analyzer.

With Roslyn you could compile all your code into syntax trees and then search those syntax trees for every expression. There will be an API that allows you to determine whether the expression was converted to anything, and if so, how the conversion analyzer classified the conversion.

We are at present in the "community technology preview" stage; we have a preliminary implementation but it is nowhere near fully featured yet. I do not remember if the method group conversion analyzer was implemented in the CTP release or not.

Give it a try, and if you have feedback about it we would love to hear your thoughts on the Roslyn forum.

Details here:

http://msdn.microsoft.com/en-us/roslyn

like image 123
Eric Lippert Avatar answered Nov 18 '22 17:11

Eric Lippert