Baig
Baig

Reputation: 1519

What is the fastest way to get values of properties from an unknown object?

I am using reflection to get property values from the unknown object. I always know the properties of the unknown object at run-time. So, I just want to get the values of those properties from that object. Reflection works for me but I have performance concerns.

Is there any other way we can achieve this efficiently? Can we use serialization? Any out of the box approach?

Upvotes: 1

Views: 1327

Answers (2)

Chaquotay inactive
Chaquotay inactive

Reputation: 2232

Some time ago I implemented a property access mechanism which uses Delegate.CreateDelegate and seemed to be faster than simple reflection. You can find it on GitHub.

Upvotes: 2

Nick Harrison
Nick Harrison

Reputation: 937

If you always know the property and you can modify the "unknown" objects, have each of the unknown objects implement a common interface. This way you can type cast the object to the interface that you define and call the properties directly.

If you cannot modify the objects directly and they are not sealed, you can derive a class from the object and mark it as implementing the interface and you are still to go.

Also, your performance concerns with reflection should not necessarily rule out using it. Run you own timing studies and see if the performance hit is really worth worrying about.

If you do use reflection and are interested in more than one property, you will be better of calling GetProperties once and looping through to find the ones that you need than to call GetProperty multiple times.

Upvotes: 0

Related Questions