Click here to Skip to main content
15,885,870 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It is not a real issue, but i have some code. That consists of an abstract class Part with 2 extension classes to it called ContentPart and MultiPartPart.

now i have a lot of lines like :

C#
Part part;
if (part is MultiPartPart){
    (part as MultiPartPart).obj1 = x;
    (part as MultiPartPart).obj2 = y;
    (part as MultiPartPart).obj3 = z;
}


Off course I could make a new MultiPartPart object and copy the pass object to it... But that is kind of out of the question, because copying the object would be just consuming more without any additional value.

but is there something like an "as" block in c#? Just like a using block?

it works like a charm how i got the code right now, but its just pagefilling all those as conversions..

Thanks in advance!
Posted

1 solution

No, there isn't.

But you are (possibly) wrong about creating an object. I would do it like this:
C#
MultiPartPart mpp = part as MultiPartPar;
if (mpp != null)
   {
   mpp.obj1 = x;
   mpp.obj2 = y;
   mpp.obj3 = z;
   }
The reason being that mpp is just a reference variable, so there is a good chance it will be optimised into a hardware register (eventually) by the JIT compiler, whereas the version you use requires a method call each time it is used because the compiler does not know that the cast operation does not have side effects you are relying on.
 
Share this answer
 
Comments
Roysten1818 23-Nov-12 9:17am    
Thanks for your explanation! so just make a reference to the original object will make it even a bit faster too i think. And it will take care of the additional text.
I'm gonna change it right now :p
OriginalGriff 23-Nov-12 9:21am    
You're welcome!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900