6

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.

Community
  • 1
  • 1
mjbates7
  • 674
  • 1
  • 6
  • 15
  • If you want to extract such information from a piece of C# code that resides in a string (_"inside a textbox"_), you'll have to parse it. Then see this question: [Parser for C#](http://stackoverflow.com/questions/81406/parser-for-c-sharp). It also contains information on reflection, which is used to look at compiled classes to extract such information. – CodeCaster Dec 05 '12 at 14:23
  • Use `Reflection` and extract the details. – droidbot Dec 05 '12 at 14:23
  • 1
    Just to clarify, you have winforms application, inside that application you have textbox where you write this class and you want to parse it, right? – Leri Dec 05 '12 at 14:24
  • What do you mean by `inside a textbox control`? – Sergey Berezovskiy Dec 05 '12 at 14:24
  • Yeah idea being user A types in the code into a textbox, then clicks "submit" in which my program then gets the items I would like from it. - no existing/compiled code. Hope that clarifies it. – mjbates7 Dec 05 '12 at 14:25

2 Answers2

11

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();    
}
Sergey Berezovskiy
  • 224,436
  • 37
  • 411
  • 441
4

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

Servy
  • 197,813
  • 25
  • 319
  • 428
Nicolas Repiquet
  • 8,727
  • 2
  • 29
  • 48