Google Answers Logo
View Question
 
Q: Programmatically Evaluating a piece of C# code for syntax correctness. ( No Answer,   1 Comment )
Question  
Subject: Programmatically Evaluating a piece of C# code for syntax correctness.
Category: Computers > Algorithms
Asked by: fatjoe10014-ga
List Price: $30.00
Posted: 30 Apr 2006 01:21 PDT
Expires: 30 May 2006 01:21 PDT
Question ID: 724060
Okay...

I have some CSharp code that can dynamically compile a statement:
***
CSharpCodeProvider provider = new CSharpCodeProvider();
CompilerParameters param = new CompilerParameters(null, "w00t.exe", true);
param.GenerateExecutable = true;
ICodeCompiler cc = provider.CreateCompiler();
CompilerResults cr = cc.CompileAssemblyFromSource(param, source);
***

Where source is a sourcecode string. Now, that is great but there is a
problem. I don't really want to compile the code, I just want to
evaluate if the syntax is correct. This particular piece of code
expects and entire namespace, class, etc to be present. In my case, I
just want to check if a small snippet of code is correct.

For example this string:

"FileStream fs = new FileStream(\"C:/newFile.txt\",
\nFileMode.Create);\nByte[] bytes = new Byte[2];\nbytes[0] =
65;\nbytes[1] = 66;\nfs.Write(bytes, 0, 2);\nfs.Close();";

Will fail to compile with the error:

error CS0116: A namespace does not directly contain members such as
fields or methods

I would like to know a way, to programatically evaluate the string
above for syntactic correctness without having to add Methods, or
namespaces to the code. The reason I don't want to do this, is because
there will be times when the code string I pass to this function may
contain a namespace, and I generally want to avoid having to write
code to detect this.

Thanks in advance.
Answer  
There is no answer at this time.

Comments  
Subject: Re: Programmatically Evaluating a piece of C# code for syntax correctness.
From: ecogiser-ga on 19 May 2006 23:29 PDT
 
It's a hard work to analyse syntax

Important Disclaimer: Answers and comments provided on Google Answers are general information, and are not intended to substitute for informed professional medical, psychiatric, psychological, tax, legal, investment, accounting, or other professional advice. Google does not endorse, and expressly disclaims liability for any product, manufacturer, distributor, service or service provider mentioned or any opinion expressed in answers or comments. Please read carefully the Google Answers Terms of Service.

If you feel that you have found inappropriate content, please let us know by emailing us at answers-support@google.com with the question ID listed above. Thank you.
Search Google Answers for
Google Answers  


Google Home - Answers FAQ - Terms of Service - Privacy Policy