I'm creating a list of nodes on the fly through a user interface. In my List I can add any number of objects (AAA, BBB, etc) to the List based on the class structure below by instantiating these objects through reflection.
public abstract class Node : IDisposable
{
protected int x;
}
public class AAA : Node
{
public int iA;
}
public class BBB : Node
{
public int iB;
}
After creating the List I want to access the the extended fields in the derived objects. I know that I have to downcast to access the extended fields but in order to do that presently I have to perform an explicit cast.
foreach (Node nn in MyList) //assume the first node in the list is AAA
{
int m = ((namespace.AAA) nn).iA; //this works
int n = (AAA) nn).iA; //this works
}
I was wondering if I can use a string to create the actual downcast. Maybe it can't be done. Maybe I'm missing something. What I would like to do which DOESN'T work would be something like the following.
foreach (Node nn in MyList) //assume the first node in the list is AAA
{
Type t2 = nn.GetType(); //{Name = AAA; FullName = namespace.AAA} (*debugger*)
string str = t2.FullName; //namespace.AAA
int m = ((str) nn).iA; //this DOESN'T work
}
When I look at the value of nn in the debugger the FullName represents the Class I want to use for the downcast.
I could get around this by using a switch statement based on the string representing the class and hard code in the cast statement but because I have over 100 different nodes and I will be adding more nodes in the future, I would have to modify the switch statement every time a node is added. This is something I would prefer not to do if all possible.
Thanks in advance for any response.
Thanks to Douglas for pointing out that I could use FieldInfo to get the value of iA for example. I just wanted to expand a little more on this topic. If I wanted to take Class AAA and extend it through composition would I also be able to access the fields in those classes through the FieldInfo.
public class AAA : Node
{
public int iA;
public X[] XArray; //where X is some other random class with pubic fields
public Y[] YArray; //where Y is some other abstract class
}