Amir Saniyan
Amir Saniyan

Reputation: 13759

How to build CodeCompileUnit from source code?

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

Upvotes: 6

Views: 6065

Answers (3)

Hans Passant
Hans Passant

Reputation: 942020

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.

Upvotes: 7

user764754
user764754

Reputation: 4236

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.

Upvotes: 6

Jason Down
Jason Down

Reputation: 22171

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:

Upvotes: 3

Related Questions