casting question

  • Thread starter Thread starter Jeroen CEuppens
  • Start date Start date
J

Jeroen CEuppens

Hi

I want to know which type the object is:
Type t=treeViewSequence.SelectedNode.GetType();

Now I know the type, so now I want to cast the following object to that
type;

LijstNode help;

(t)help;

help=(t)treeViewSequence.SelectedNode;



But this doesn't work :-(



How should i get these working?



THX

JC
 
You approach this the wrong way. The type of the left side of the assignment
is always known. It (if anything) needs to be used in a cast
In your case:

ListNode help = (ListNode)treeViewSequence.SelectedNode;

Don't worry, The runtime type information won't go away
 
See this code:

LijstNode copy;


copy=(LijstNode)treeViewOverview.SelectedNode;

switch (copy.ID)

{

case 10: copy=(LijstNode)CyclopNode.Clone();break;

case 11: copy=(LijstNode)FileNode.Clone(); break;

case 2: copy=(LijstNode)ViewNode.Clone(); break;

case 30: copy=(LijstNode)ColormapGrayNode.Clone(); break;

case 31: copy=(LijstNode)ColormapJetNode.Clone(); break;

}

The selectedNode can be a LijstNode, a CyclopNode, a ColormapNode, ...... it
are nodes derived from TreeNode which each different functions

So i need to know which type the selectednode is, so I can cast it to that
type en copy it in copy......

Do you understand?



Hope you can help, thx

JC
 
If you have a base class A and several derived classes A1, A2 and A3 then
you can check the runtime type like this:

class A1: A
{
}

class A2: A
{
}

class A3: A
{
}

public A GetObjInstance()
{
if ( some condition )
return new A1();
else if ( some other condition )
return new A2();
else if ( another condition )
return new A3();
}

A a = GetObjInstance();
if ( a is A1 )
{
A1 a1 = (A1)a;
// do something
}
else if ( a is A2 )
{
A2 a2 = (A2)a;
// do something
}
else if ( a is A3 )
{
A3 a3 = (A3)a;
// do something
}
 
Back
Top