In C# is there a way to convert a function's source code to a string? Sort of like how it can be done in JavaScript. I need this because I'm writing some documentation for an Asp.Net control and want to show the original source code next to the result, without copy/pasting it.
5 Answers
Short answer: no.
Long answer: you can generate something at compile time with MSBuild tasks, T4 templates, or manually parsing stuff, or using Roslyn to parse it for you.
If you need the source code at runtime though, you'll surely need to include the cs files in the deployed stuff, because there is no stable way of getting the code back. (You could try runtime decompilation though, but that will look "ugly" and not very precise.)
Comments
The cheating way:
include the .cs file in your project, and read from that.
5 Comments
Sounds like you want the function to do a task while it is in run-time being executed, to write (its) source code in a text file. That is not possible since the function runs as ASSEMBLY (or binary) once it is in run time.
You could however have the function read a copy of its source code from somewhere then write it somewhere else
Comments
You can run C# compiler as a separate process (it's part of .Net Framework and is available for free - do the synchronization with it then) and load generated assembly or emit IL code using proper methods (you have to generate "real" IL code first to prepare such small templates for you first-just write c# class and inspect how generated IL code looks like). Check if yo have proper permissions to do it first.
Sample Emit usage is here for instance (I wrote it some time ago): http://bitcare.codeplex.com/SourceControl/changeset/view/21192#366441