Is there a way to cast an instance of a class using a Type variable rather then an explicitly provided type?
For example in my method below ‘this’ is a derived type of ‘Node’. I want the method to repeatedly try to get a value from GetNodeIntrinsicProperty() after which if it get’s a null value it should cast itself as it’s base type and try again.
Basically, I want to call every implementation of GetNodeIntrinsicProperty() until I get a value.
public string GetIntrinsicProperty(String propertyKey) { //sets the original type value Type currType = this.GetType(); Node thisNode = this; String propertyValue; while (currType is Node) { //casts thisNode as CurrType thisNode = thisNode as currType; /*The live above gives me the following error * * Error 20 The type or namespace name 'currType' could not be found (are you missing a using directive or an assembly reference?) */ //trys to get the property with the current cast //GetNodeIntrinsicProperty() is defined seperately in each type propertyValue = thisNode.GetNodeIntrinsicProperty(propertyKey); if (propertyValue != null) { return propertyValue; } //sets CurrType to its base type currType = currType.BaseType; } return null; }
Ok, so first the answer to your question.
I’m assuming you have some structure like this:
The implementation of GetIntrinsicProperty above will do what you’re asking, but I would suggest that it’s wrong.
You’re forcing a child class to exactly replicate your signature and a developer to understand what you want. This is what virtual methods are for. If I’m understanding you correctly the proper way to do what you want is this:
The idea of virtual methods is that the type of your variable doesn’t determine which implementation is called, but rather the run time type of the object determines it.
As far as I can tell, the situation you’re describing is one where you are trying do your own dispatch to the implementation of a method on the runtime type of the object. Pretty much the definition of a virtual method.
If I didn’t get the question right, please clarify. 🙂