Folks, FYI -- on the weekend I hit the situation where I had lots of small
pieces of similar code and I wanted it to configure their behaviour. I
could have created a fancy set of parameters and more complicated code to
apply them, but I decided the most desirable thing was to "script" the
code. I've seen some apps and tools that compile C# source on-the-fly but
I've never needed to do it myself until now. I thought it would be really
difficult, but it's not. Here's the skeleton of my code:
var provider = new CSharpCodeProvider();
var parameters = new CompilerParameters();
parameters.GenerateInMemory = true;
parameters.ReferencedAssemblies.Add("System.Security.dll");
parameters.GenerateExecutable = false;
var results = provider.CompileAssemblyFromSource(parameters, mySourceCode);
if (results.Errors.HasErrors || results.Errors.HasWarnings) {
/* do something with the error numbers and messages */
return;
}
Type[] types = results.CompiledAssembly.GetTypes();
So you finish up with an in-memory Assembly and you can use reflection to
get types and Invoke members. Don't forget to use *dynamic* on the
reflected types to make your reflection code shorter and more readable.
Overall, the resulting code is a little bit fiddly, but it's a powerful
technique that's overlooked by a lot of developers.
*Greg K*