Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to build CodeCompileUnit from source code?

Tags:

c#

codedom

How to build CodeCompileUnit from source code?

What is the best way to parse a C# source code(s)?

Is CodeCompileUnit a correct selection? and howto?

Thanks

like image 374
Amir Saniyan Avatar asked Jul 19 '11 22:07

Amir Saniyan


3 Answers

You've got that backwards, CodeCompileUnit is there to generate source code. If you already have the source code then you only need a class that inherits CodeDomProvider to compile the code. Like Microsoft.CSharp.CSharpCodeProvider or Microsoft.VisualBasic.VBCodeProvider.

There are some odds that you are asking about parsing an existing source code file. That's what the System.CodeDom.Compiler.CodeParser was intended to do. There are no existing concrete implementations of that abstract class, there will never be any. This blog post explains why.

like image 77
Hans Passant Avatar answered Oct 14 '22 07:10

Hans Passant


You can do it with CodeSnippetCompileUnit which is a subclass of CodeCompileUnit:

string source = @"
using System;
namespace SomeNamespace 
{
  public class Class0
  {     
  }
}";

var csu0 = new CodeSnippetCompileUnit(curSource);

Additional Info:

If you have multiple units you can put them together to generate an assembly:

CodeDomProvider provider = new CSharpCodeProvider();
CompilerResults results = provider.CompileAssemblyFromDom(new CompilerParameters(), csu0, csu1 /*arbitrary number*/);

Of course it it possible that classes from all of these CodeSnippetCompileUnit reference each other.

like image 29
user764754 Avatar answered Oct 14 '22 08:10

user764754


Your question is kind of vague. Are you looking for a tutorial? Do you have a specific task you are trying to implement? Specific questions are the essence of Stackoverflow. That aside, I'll just give you some places that may be helpful for starting out:

  • MSDN documentation on CodeDOM
  • Dynamic Code Integration with CodeDom
  • CodeDOM Assistant
like image 3
Jason Down Avatar answered Oct 14 '22 08:10

Jason Down