Click here to Skip to main content
13,143,708 members (29,881 online)
Rate this:
Please Sign up or sign in to vote.
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 :

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 23-Nov-12 2:51am

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1

No, there isn't.

But you are (possibly) wrong about creating an object. I would do it like this:
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.
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy |
Web04 | 2.8.170915.1 | Last Updated 23 Nov 2012
Copyright © CodeProject, 1999-2017
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100