Stuart Moore
Stuart Moore

Reputation: 801

Is there a library to perform reflection on .Net objects based on a string?

I'm looking for a library that would allow you to perform reflection on an object using a string, e.g.

class SampleClass {
    public SampleClass Child {get; set;}
    public string SomeValue {get;set;}
}
var a = new SampleClass { Child = new SampleClass { SomeValue = "v"}};
var parser = new ReflectionParser();
var result = parser.Parse("Child.SomeValue", a);
// result is "v"

If not, I'm considering writing one and open sourcing it - but I didn't want to re-invent the wheel. Initially it would just get property values, but in the longer term I could see it gaining the ability to running methods, parsing arguments as need be.

The closest I have found is an XPath style library https://code.google.com/archive/p/antix-software/wikis/AntixReflectionQuery.wiki referenced in Using an XPath-style Query with Reflection and Traversing an arbitrary C# object graph using XPath/applying XSL transforms - however this doesn't appear to be available any more.

Upvotes: 1

Views: 262

Answers (1)

Heinzi
Heinzi

Reputation: 172200

The .NET base class library contains a DataBinder class which does exactly what you want.

It was designed for ASP.NET WebForms databinding, so it's in the System.Web.UI namespace and requires a reference to System.Web. But don't let that stop you, it can be used outside of web projects just as well.

class SampleClass
{
    public SampleClass Child { get; set; }
    public SampleClass[] Children { get; set; }
    public string SomeValue { get; set; }
}

var a = new SampleClass { Child = new SampleClass { SomeValue = "v" } };

var result = DataBinder.Eval(a, "Child.SomeValue");
Console.WriteLine(result); // yields v

DataBinder also supports indexing over collections, so Children[0].SomeValue would also be evaluated correctly:

var a = new SampleClass { Children = new SampleClass[] { new SampleClass { SomeValue = "v" } } };

var result = DataBinder.Eval(a, "Children[0].SomeValue");
Console.WriteLine(result); // yields v

Upvotes: 2

Related Questions