C#: at design time, how can I reliably determine the type of a variable that is declared using var?

Posted by Cheeso on Stack Overflow See other posts from Stack Overflow or by Cheeso
Published on 2010-05-15T15:21:12Z Indexed on 2010/05/15 15:24 UTC
Read the original article Hit count: 195

Filed under:
|
|
|

I'm working on a completion (intellisense) facility for C# in emacs.

The idea is, if a user types a fragment, then asks for completion via a particular keystroke combination, the completion facility will use .NET reflection to determine the possible completions.

Doing this requires that the type of the thing being completed, be known. If it's a string, it has a set of known methods; if it's an Int32, it has a separate set of methods, and so on.

Using semantic, a code lexer/parser package available in emacs, I can locate the variable declarations, and their types. Given that, it's straightforward to use reflection to get the methods and properties on the type, and then present the list of options to the user.

The problem arrives when the code uses var in the declaration.

How can I reliably determine the actual type used, when the variable is declared with the var keyword? Just to be clear, I don't need to determine it at runtime. I want to determine it at "Design time".

So far the best idea I have is:

  • extract the declaration statement, eg var foo = "a string value";
  • concatenate a statement foo.GetType();
  • dynamically compile the resulting C# fragment it into a new assembly
  • load the assembly into a new AppDomain, run the framgment and get the return type.
  • unload and discard the assembly

This sounds awfully heavyweight, for each completion request in the editor.

Any better ideas out there?

© Stack Overflow or respective owner

Related posts about c#

Related posts about reflection