Parse c# class file to get properties and methods

.net, c#, reflection, regex, winforms

Solution

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();    
}

Problem

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.

Original source

Related problems