Click here to Skip to main content
Sign Up to vote bad
good
See more: C#objectClass
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:51


1 solution

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 - 23 Nov '12 - 9:17
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:21
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
Your Filters
Interested
Ignored
     
0 Mahesh Bailwal 353
1 Sergey Alexandrovich Kryukov 339
2 Maciej Los 290
3 CPallini 245
4 Rohan Leuva 175
0 Sergey Alexandrovich Kryukov 9,162
1 OriginalGriff 7,194
2 CPallini 3,923
3 Rohan Leuva 3,176
4 Maciej Los 2,633


Advertise | Privacy | Mobile
Web01 | 2.6.130516.1 | Last Updated 23 Nov 2012
Copyright © CodeProject, 1999-2013
All Rights Reserved. Terms of Use
Layout: fixed | fluid