C# Reflection: "Pointer" to a value type

Short description

I want to know if there is a .NET feature letting me manipulate a value type obtained by reflection. So when calling PropertyInfo.getValue(...) on a value type property I want to not get a copy, but the original object and manipulate it.

I am NOT allowed to use unsafe pointers.

Long description

This requirement arose because I am implementing a webservice letting me manipulate a Unity3d scene graph.

The scene graph might have the following structure

  • GameObject 1
    • Vector 1.2
  • GameObject 2
    • Struct 2.1
    • Vector 2.2

A client can query the following URI:

GET http://.../GameObject2/StructProperty/someProperty

This works, as it is as simple as traversing the hierarchy via reflection, searching for the property by name (e.g. Struct or Vector) and calling getValue on the corresponding PropertyInfo, returning this to the client.

But a client can also query:

POST http://.../GameObject2/VectorProperty/xProperty with e.g. 5.4 as the entity body. The x property of the Vector should then be set to 5.4

What I am doing at the moment is traversing the graph forward (like with GET) till I find the Vector object. Then I am doing a recursive setValue UNTIL I am doing the setValue on a reference type e.g.

object2.setValue(Vector.setValue(5.4));

(for simplicity I am omitting the PropertyInfo part. Assume it is there)

So I must be able to query an arbitrary object hierarchy containing both value types and reference types. Is there a better way for what I am doing?

Jon Skeet
people
quotationmark

So when calling PropertyInfo.getValue(...) on a value type property I want to not get a copy, but the original object and manipulate it.

Then you need access to the field, not the property. Alternatively, you need to call the getter to retrieve a copy of the value, modify the copy, and then call the setter to change the state of the containing object.

That's not just true when you use reflection - it's true in general. You can't do something like:

foo.Position.X = 10;

where Position is a property whose type is a value type. You'll get a compile-time error. Instead, you'd need something like:

var position = foo.Position;
position.X = 10;
foo.Position = position;

You can do that with reflection - assuming that there is a setter, of course.

Note that when you say "the original object" here, for a value type (stored in a field of that type, i.e. not boxed) there is no object. There's just the value, as a field as part of another object.

people

See more on this question at Stackoverflow