Sergei
Sergei

Reputation: 1637

Library for traversing object property tree on C#

I want to have a method that could traverse an object by property names and get me the value of the property.

More specifically as an input I have a string like "Model.Child.Name" and I want this method to take an object and get me the value that could be found programatically via: object.Model.Child.Name.

I understand that the only way to do this is to use Reflection, but I don't want to write this code on my own, because I believe that there are pitfalls. Moreover, I think it is more or less usual task.

Is there any well-known implementation of algorithm like that on C#?

Upvotes: 2

Views: 1871

Answers (2)

Chuck Conway
Chuck Conway

Reputation: 16435

The is not that difficult to write. Yes there are some pitfalls, but it's good to know the pitfalls.

The algorithm is straightforward, it's traversing a tree structure. At each node you inspect it for a primitive value (int, string, char, etc) if it's not one of these times, then its a structure that has one or more primitives and needs to be traversed to it's primitives.

The pitfalls are dealing with nulls, nullable types, value versus reference types, etc. Straight forward stuff that every developer should know about.

Upvotes: 1

Tilak
Tilak

Reputation: 30718

Reflection is the way to go.

Reflection to access properties at runtime

You can take a look at ObjectDumper and modify the source code as per your requirement.

ObjectDumper take a .NET object and dump it to string, file, textWriter etc.

Upvotes: 2

Related Questions