Dear All,
I am really struggling on this with new changes in Revit API 2022. Could some one help me with this?
I am trying to set a variable value, for some reason, based on the current document unit. I had this in previous versions implemented using a switch case. Here is my code;
this.displayUnitType = this.doc.GetUnits().GetFormatOptions(UnitType.UT_Length).DisplayUnits;
switch (this.displayUnitType)
{
case DisplayUnitType.DUT_METERS:
this.docUnitCode = 0;
break;
case DisplayUnitType.DUT_CENTIMETERS:
this.docUnitCode = 1;
break;
case DisplayUnitType.DUT_MILLIMETERS:
this.docUnitCode = 2;
break;
case DisplayUnitType.DUT_DECIMAL_FEET:
this.docUnitCode = 3;
break;
}
I am sorry but getting too much confused with the new ForgeTypeId / SpecTypeId and UnitTypeId. However, I tried this code below but Visual Studio throws the error saying that the 'case' expects a constant value.
this.docUnitType = this.doc.GetUnits().GetFormatOptions(SpecTypeId.Length).GetUnitTypeId();
switch (this.docUnitType.TypeId)
{
case UnitTypeId.Meters.TypeId:
this.docUnitCode = 0;
break;
case UnitTypeId.Centimeters.TypeId:
this.docUnitCode = 1;
break;
case UnitTypeId.Millimeters.TypeId:
this.docUnitCode = 2;
break;
case UnitTypeId.Feet.TypeId:
this.docUnitCode = 3;
break;
}
Same time, if I try this code below, it works perfectly fine.
var docUnitType = doc.GetUnits().GetFormatOptions(SpecTypeId.Length).GetUnitTypeId();
if (docUnitType.TypeId == UnitTypeId.Millimeters.TypeId)
{
TaskDialog.Show("Message", "Millimeters...");
}
Why is it not working with Switch Case?
Solved! Go to Solution.
Solved by RPTHOMAS108. Go to Solution.
More of a limitation of C# case thing rather than Revit thing. Case comparison needs to be based on constants. The DisplayUnitType was an enum of such constants.
ForgeTypeId implements the equality operator however. So if you are only comparing a small number of possible units then you can do as follows to achieve similar to what you were aiming for (deal with -1 for item not found in array).
public Result TObj64a(Autodesk.Revit.UI.ExternalCommandData commandData,
ref string message, Autodesk.Revit.DB.ElementSet elements)
{
Document Doc = commandData.Application.ActiveUIDocument.Document;
ForgeTypeId UTid = Doc.GetUnits().GetFormatOptions(SpecTypeId.Length).GetUnitTypeId();
ForgeTypeId[] Choices = new ForgeTypeId[] { UnitTypeId.Meters, UnitTypeId.Centimeters, UnitTypeId.Millimeters, UnitTypeId.Feet};
int x = Array.IndexOf(Choices, UTid);
TaskDialog.Show("Units", x.ToString());
return Result.Succeeded;
}
Personally I think it is better to not be creating your own versions of internal Revit listings for units etc. i.e. no real point changing a ForgeTypeId to your own Integer representation of it. You just spend a lot of time maintaining such lists of relationships.
Thanks a lot for the clarification. I take your advice with full respect. I will change my implementation not to have my own integer representations.