Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse c# class file to get properties and methods [duplicate]

Possible Duplicate:
Parser for C#

Say if I had a simple class such as inside a textbox control in a winforms application:

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

    public void DoSomething(string x)
    {
        return "Hello " + x;
    }
}

Is there an easy way I can parse the following items from it:

  • Class Name
  • Properties
  • Any public methods

Any ideas/suggestions appreciated.

like image 537
mjbates7 Avatar asked Dec 05 '12 14:12

mjbates7


2 Answers

You can use Reflection for that:

Type type = typeof(Person);
var properties = type.GetProperties(); // public properties
var methods = type.GetMethods(); // public methods
var name = type.Name;

UPDATE First step for you is compiling your class

sring source = textbox.Text;

CompilerParameters parameters = new CompilerParameters() {
   GenerateExecutable = false, 
   GenerateInMemory = true 
};

var provider = new CSharpCodeProvider();       
CompilerResults results = provider.CompileAssemblyFromSource(parameters, source);

Next you should verify if your text is a valid c# code. Actually your code is not valid - method DoSomething marked as void, but it returns a string.

if (results.Errors.HasErrors)
{
    foreach(var error in results.Errors)
        MessageBox.Show(error.ToString());
    return;
}

So far so good. Now get types from your compiled in-memory assembly:

var assembly = results.CompiledAssembly;
var types = assembly.GetTypes();

In your case there will be only Person type. But anyway - now you can use Reflection to get properties, methods, etc from these types:

foreach(Type type in types)
{
    var name = type.Name;  
    var properties = type.GetProperties();    
}
like image 76
Sergey Berezovskiy Avatar answered Sep 21 '22 05:09

Sergey Berezovskiy


If you need to analyse C# code at runtime, take a look at Roslyn.

like image 27
Nicolas Repiquet Avatar answered Sep 19 '22 05:09

Nicolas Repiquet