How can I read the properties of a C# class dynamically? *

Question

I can do an eval("something()"); to execute the code dynamically in JavaScript. Is there a way for me to do the same thing in C#?

What I am exactly trying to do is that I have an integer variable (say i) and I have multiple properties by the names: "Property1", "Property2", "Property3", etc. Now, I want to perform some operations on the " Property*i* " property depending on the value of i.

This is really simple with Javascript. Is there any way to do this with C#?

Answer

Unfortunately, C# isn't a dynamic language like that.

What you can do, however, is to create a C# source code file, full with class and everything, and run it through the CodeDom provider for C# and compile it into an assembly, and then execute it.

This forum post on MSDN contains an answer with some example code down the page somewhat:
create a anonymous method from a string?

I would hardly say this is a very good solution, but it is possible anyway.

What kind of code are you going to expect in that string? If it is a minor subset of valid code, for instance just math expressions, it might be that other alternatives exists.


Edit: Well, that teaches me to read the questions thoroughly first. Yes, reflection would be able to give you some help here.

If you split the string by the ; first, to get individual properties, you can use the following code to get a PropertyInfo object for a particular property for a class, and then use that object to manipulate a particular object.

String propName = "Text";
PropertyInfo pi = someObject.GetType().GetProperty(propName);
pi.SetValue(someObject, "New Value", new Object[0]);

Link: PropertyInfo.SetValue Method

< br > via < a class="StackLink" href=" http://stackoverflow.com/questions/4629/" >How can I read the properties of a C# class dynamically?< /a>
Share on Google Plus

About Cinema Guy

This is a short description in the author block about the author. You edit it by entering text in the "Biographical Info" field in the user admin panel.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment