How do I access a certain field of 'object' without casting it to one type when it can be several types?

c#, casting, object, type-conversion

Solution

The best option would be to make all of your classes implement a common interface, and then use that interface to access the properties.

However, if these are classes outside of your control, there are other options. You could use Reflection to access the field/property (via Type.GetField and FieldInfo.GetValue, etc), though this is slow at runtime.

If you're using C# 4 or later, you can use `dynamic`:

dynamic theObject = yourObject;
Point position = theObject.Position;

This will use dynamic (runtime) binding to find the `Position` property or field on your type.

Problem

I have an object that can be assigned different classes, all of which have a `Position` field which I need to access regardless of the object's type. Visual Studio won't let me compile `var pos = myObject.Position` because `object` doesn't have a `Position` field. And I can't cast to `MyClass`, because there can be several other classes assigned to that variable. How do I access the `Position` field without casting to one type?

Original source