I found this thread on direct casting from Through the Interface:
http://through-the-interface.typepad.com/through_the_interface/2006/09/working_with_sp.htmlSome thoughts from the Autodesk labs. All the code below is taken from Lab 5.
Direct casting is used through out for layertable, blocktable and blocktablerecord in the Labs. With these is there ever a chance it could not return these objects?
In the labs direct casting is used with try catch statements where the exception is used in similar way to if-else statement.
They use entity within a block here:
Entity ent = (Entity)trans.GetObject(id, OpenMode.ForRead, false);
if (ent is AttributeDefinition)
Below code is called on items selected by the user: Is Gettype() and typeof() interchangeable with IS as shown above?
Entity ent = (Entity)trans.GetObject(employeeId, OpenMode.ForRead, false); // Use it to open the current object!
if (ent.GetType() == typeof(BlockReference)) // We use .NET's RTTI to establish type.
This is their layer create:
private ObjectId CreateLayer()
{
ObjectId layerId;
Database db = HostApplicationServices.WorkingDatabase;
using (Transaction trans = db.TransactionManager.StartTransaction())
{
//Get the layer table first...
LayerTable lt = (LayerTable)trans.GetObject(db.LayerTableId, OpenMode.ForRead);
//Check if EmployeeLayer exists...
if (lt.Has("EmployeeLayer"))
{
layerId = lt["EmployeeLayer"];
}
else
{
//If not, create the layer here.
LayerTableRecord ltr = new LayerTableRecord();
ltr.Name = "EmployeeLayer"; // Set the layer name
ltr.Color = Color.FromColorIndex(ColorMethod.ByAci, 2);
// upgrade the open from read to write
lt.UpgradeOpen();
layerId = lt.Add(ltr);
trans.AddNewlyCreatedDBObject(ltr, true);
}
trans.Commit();
}
return layerId;
}
******************EDIT***********************
I thought I would run a test on Lab 5
Ran the command and then purged and then ran command again
It threw an exception here:
BlockTableRecord empBtr = (BlockTableRecord)trans.GetObject(bt["EmployeeBlock"], OpenMode.ForRead);
It detected that the block and layer had been deleted and created them again so not sure what is happening here.