casting

  • Thread starter Thread starter juli jul
  • Start date Start date
J

juli jul

Hello,
I want to do casting of class A object to class B object.
How exactly can I do it in c#?
The casting I need is: The client will do a casting to a class instance
and I will cast it to another class instance with proper changes.
How to do it?
Thanks!
 
juli jul said:
Hello,
I want to do casting of class A object to class B object.
How exactly can I do it in c#?
The casting I need is: The client will do a casting to a class instance
and I will cast it to another class instance with proper changes.
How to do it?
Thanks!

How are the classes related:

1. the one the client receives
2. the one they cast it to
3. the one you will cast it to

Regards

Richard Blewett - DevelopMentor
http://www.dotnetconsult.co.uk/weblog
http://www.dotnetconsult.co.uk
 
If I understand you correctly: ((B)oA).<property or method>
But I would use the "as" operator instead and then test for null:

B oB = oA as B;
if (oB != null)
{
<do something with oB>
}

Hope this helps.
 
I forgot to state the obvious, A and B should be related in some way like
derived from the same class or interface or each other.
 
B oB = oA as B;
I would prefer

((B oA).<do something>

as it will throw a meaningful exception if oA is not a B, instead of
doing nothing.
 
Mark Wilden said:
I would prefer

((B oA).<do something>

as it will throw a meaningful exception if oA is not a B, instead of
doing nothing.

Yes - so would I, very definitely, *if* it really should be that type.
(That's actually the more common case at the moment, I find - generics
may well change that though.)
 
Back
Top