How to build CodeCompileUnit from source code?
Asked Answered
S

3

6

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

Sternpost answered 19/7, 2011 at 22:11 Comment(1)
From your question it is not really what you want to achive... do you need to compile some C# code and then run it and/or save it (as .dll or .exe) ?Inquisitorial
J
7

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.

Jeweller answered 19/7, 2011 at 23:5 Comment(0)
L
6

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.

Labialized answered 27/10, 2012 at 19:38 Comment(1)
This is what I'm looking forSyndesmosis
R
3

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:

Ramires answered 19/7, 2011 at 23:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.