question

RobertGustafson-1682 avatar image
0 Votes"
RobertGustafson-1682 asked RobertGustafson-1682 commented

How can I (say, usimg reflection) get a reference to an object instance's BASE-class instance, or to a property thereof?

WHAT I HAVE:
Visual Basic 2019, .NET Framework 4.0+/.NET Core

MY ISSUE:
I've noticed that within a class, Me.property and MyBase.property refer to 2 very different things. What, however, if I want to access MyBase.property (or MyBase, for that matter) from outside of Me? That is, what if, given object, I want to access baseofobject.property instead of object.property, or simply get a reference to baseofobject? (And, when creating things like inherited controls, access to MyBase.property is important, and not always within the class of Me.) I figure there's a way to do that, via reflection. What is it? Please keep any answers in VB.NET and as simple as possible.






dotnet-visual-basicdotnet-runtime
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

1 Answer

Viorel-1 avatar image
0 Votes"
Viorel-1 answered RobertGustafson-1682 commented

Try something like this:

Dim b As BaseClass = obj

where obj is your object of inherited type, BaseClass is the type of the base.

Then you can use b.property to access the base property, or obj.property to access the new property defined in inherited class.

You can also write CType(obj, BaseClass).property.


· 3
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

This approach only works when a property is Shadowed in a derived class. If it is Overriden, then CType(obj, BaseClass).property still returns obj.Property. Is there a way to get the BaseClass version of property when overriding?







0 Votes 0 ·
Viorel-1 avatar image Viorel-1 RobertGustafson-1682 ·

The solution is different for this new case.


0 Votes 0 ·

What is it?! I need an approaches for both Shadowed and Overridden properties!

0 Votes 0 ·