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?
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:This will use dynamic (runtime) binding to find the
Positionproperty or field on your type.