Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Type conversion

Status
Not open for further replies.

flnhst

Programmer
Aug 9, 2005
12
NL
I have the class CItem, with a derived class called CItemBox.

I can easily cast an CItem to CItemBox with this:

Code:
((CItemBox)InstanceOfCItem).MethodOfCItemBox();

but how can i cast when i have a Type class instance of CItemBox?

This doesnt work:

Code:
((typeof(CItemBox))InstanceOfCItem).MethodOfCItemBox();

is there anyway to do this? Cast with only a Type instance of CItemBox?
 
If all you want to do is invoke the MethodOfCItemBox, you would get the MethodInfo object for the method, then invoke it. This involves using reflection, and is somewhat slow, but will allow you to do what you want.
Code:
try
{
  Type itemBoxType = typeof(CItemBox);
  MethodInfo myMethod=type.GetMethod("MethodOfCItemBox");
}
catch (AmbiguousMatchException ame)
{
   // TODO: Log error
   return;
}
catch (ArgumentNullException ane)
{
   // TODO: Log error
   return;
}

try
{
   if (myMethod!=null)
   {
      object returnValue = myMethod.Invoke(null, new object[]{MethodOfCItemBoxArgsGoHere});
   }
}
catch (TargetInvocationException tie)
{
   // TODO: Log error
   return;
}
// NOTE: Other exceptions could be raised as well
Also - a style note. Prefixing class names with "C" is deprecated in C#. Here's some videos from Brad Abrams at Microsoft that discuss good practice.


Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
CItemBox doesnt contain any methods, only some public variables of string and int types.

Is there anyway to cast this way?
 
Umm, so why did you use a method name like [tt]MethodOfCItemBox[/tt] in your post?

If you want to access a property of a type, you'd use the PropertyInfo class. Invoking it is similar to calling a method.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top