Create an account

Very important

  • To access the important data of the forums, you must be active in each forum and especially in the leaks and database leaks section, send data and after sending the data and activity, data and important content will be opened and visible for you.
  • You will only see chat messages from people who are at or below your level.
  • More than 500,000 database leaks and millions of account leaks are waiting for you, so access and view with more activity.
  • Many important data are inactive and inaccessible for you, so open them with activity. (This will be done automatically)


Thread Rating:
  • 623 Vote(s) - 3.43 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to dynamically get a property by name from a C# ExpandoObject?

#1
I have an `ExpandoObject` and want to make a getter for it that will return a property by name at runtime, where the name is specified in a string instead of hardcoded.

For example, I CAN do this:

account.features.isEmailEnabled;

and that will return true. `account` is a `ExpandoObject`, and `features` is also an `ExpandoObject`. So I have an `ExpandoObject` that contains other `ExpandoObjects`.

So what I want to be able to do is this:

account.features.GetProperty("isEmailEnabled");

and have that return true.

The reason is that I have many features, and I want to be able to write one generic getter method where I can pass in the name of the feature I want, and the method will pass me back the value for account.features.whatever (where "whatever" is specified by passing in a string to the generic getter method). Otherwise I am going to have to write 30-some getters one for each feature.

I did a lot of research and tried doing something like:

var prop = account.features.GetType();
// this returns System.Dyanmic.ExpandoObject
followed by

var value = prop.GetProperty(featureNameAsString);

but `value` always comes back as null. I don't understand why. In the watch window I can do `account.features.isEmailEnabled` and it shows true and says its a boolean. But if I try to get at this value using the approach above and pass in `isEmailEnabled` as the `featureNameAsString` I just get null.

Can someone please tell me what I may be doing wrong and what's a good approach, without it being too complex?

I am working with ASP.NET under the 4.5.1 framework.
Reply

#2
`ExpandoObject` provides access both via `dynamic` and via `IDictionary<string,object>` - so you could just use the dictionary API:

var byName = (IDictionary<string,object>)account.features;
bool val = (bool)byName["isEmailEnabled"];

Or if the name is fixed, just:

bool val = ((dynamic)account).features.isEmailEnabled;
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

©0Day  2016 - 2023 | All Rights Reserved.  Made with    for the community. Connected through