Ok, so you’ve got a bunch of entities in a collection. You only want to deal with circles. You need to iterate through the collection and consider only the circles. But how will you identify the circles from the other objects.
- Casting.
You can cast
Entity en = en as Circle
And then you can test whether entity is null.
If (en == null )
{ // throw new Exception etc. etc. }
Or you can try the equivalent:
If (en is Circle)
{ // Perform operation etc. etc.}
What is the catch with this approach?
- The benefits are that it is really quick and dirty.
- ………most important that you gotta watch out for is that it tests for Circles and subsequent sub classes of circles. You may not want that so watch out!
- GetType
I’ve also seen folks on the forums use the Gettype to check for the type of the entity. It goes something like this:
en.GetType() == typeOf(Circle)
The Catch with this approach
- It’s painful to read.
- Two computations involved, just like the first approach. I can’t see the performance being too much better or worse.
Another approach is to use Dxf codes to check for the name. But this is overcomplicated. I don’t see many people using it on the forums and you need the object ID of the relevant entity and all the overhead associated with it.
In my opinion, keep it simple. Casting, after all things considered, is probably the best option, but you have to watch out – all subclasses will return true. So you need to use the most granular class you can if that is at all important.
Leave a Reply