Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# object
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 3:51am

1 solution

Rate this: bad
good
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.
  Permalink  
Comments
Roysten1818 at 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 at 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
0 OriginalGriff 475
1 Maciej Los 349
2 Richard MacCutchan 220
3 BillWoodruff 219
4 Mathew Soji 160
0 OriginalGriff 8,759
1 Sergey Alexandrovich Kryukov 7,407
2 DamithSL 5,639
3 Maciej Los 5,269
4 Manas Bhardwaj 4,986


Advertise | Privacy | Mobile
Web01 | 2.8.1411028.1 | Last Updated 23 Nov 2012
Copyright © CodeProject, 1999-2014
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