Hi guys,
I work in the same office as both Gopinath andf Albert Szilvasy (Albert being the architect for the AutoCAD .NET API), so I was able to quickly sort this out. Unfortunately, Gopinath misunderstood an answer Albert gave when he quizzed him on this, and so made a mistake with the advice he gave in his AU class. Sorry about that. Here is the correct information - straight from the brain of Albert ...
You don't have to Dispose of a DBObject that was already part of the DWG database and which you open in a Transaction. An example of this is:
[CommandMethod("ChgLayerNames")]
public static void ChangeLayerNames()
{
Database db = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForRead);
foreach (ObjectId ltrId in lt)
{
//No need to have using statement for the ltr's we open. No need to call Dispose()
LayerTableRecord ltr = (LayerTableRecord)tr.GetObject(ltrId, OpenMode.ForRead);
if (ltr.Name != "0")
{
ltr.UpgradeOpen();
ltr.Name = "First Floor " + ltr.Name;
}
}
tr.Commit();
}
}
You can use a using statement in the above if you really want to, but it just makes your code harder to read.
You should use a using statement if you create a DBObject you intend to add to a Transaction. This is because you can't assume that an exception won't be thrown before you add the DBObject to the Transaction once the object is added to the transaction, its safe to leave AutoCAD to Dispose of the .NET wrapper for the object you added).
[CommandMethod("AddLyr")]
public static void AddLayer()
{
Database db = Application.DocumentManager.MdiActiveDocument.Database;
using (Transaction tr = db.TransactionManager.StartTransaction())
{
LayerTable lt = (LayerTable)tr.GetObject(db.LayerTableId, OpenMode.ForWrite);
LayerTableRecord ltr;
//Use a using stament here because an exception may be thrown before we can
// add the DBObject to the Transaction.
using (ltr
= new LayerTableRecord
()) {
ltr.Name = "Test";
lt.Add(ltr);
tr.AddNewlyCreatedDBObject(ltr, true);
}
tr.Commit();
}
}
Sorry again for this misunderstanding. I hope you've not all spent time going back and adding redundant 'using' satetments to your codebase.
edit->kdub code = csharp formatting