Reputation: 1219
In Revit API, when you want to get a parameter, you send its enum
then fetch it and you convert it to the type you want.
But sometimes the parameter is missing so it return null
, and null.AsDouble()
or null.AsValueString()
throws a null exception
.
I retrieve so many parameters and I am using ternary operators but I am not sure that this is the best way to handle this
string typemark = e.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_MARK)!=null?wt.get_Parameter(BuiltInParameter.ALL_MODEL_TYPE_MARK).AsValueString():"";
double cost = e.get_Parameter(BuiltInParameter.ALL_MODEL_COST)!=null?wt.get_Parameter(BuiltInParameter.ALL_MODEL_COST).AsDouble():0;
I was thinking of doing a function that is more generic, to pass the parameter and the type that I want to convert the result to.
public static T CheckParameterAndFetch<T>(this Element e, BuiltInParameter p, Type t)
{
if (e.get_Parameter(p) != null)
{
if (t.GetType() == typeof(string))
{
return (T)Convert.ChangeType(e.get_Parameter(p).AsValueString(), typeof(string));
}
else if (t.GetType() == typeof(double))
{
return (T)Convert.ChangeType(e.get_Parameter(p).AsDouble(), typeof(double));
}
else if (t.GetType() == typeof(int))
{
return (T)Convert.ChangeType((int)e.get_Parameter(p).AsDouble(), typeof(double));
}
}
else
{
if (t.GetType() == typeof(string))
{
return (T)Convert.ChangeType("", typeof(string));
}
else if (t.GetType() == typeof(double))
{
return (T)Convert.ChangeType(0, typeof(double));
}
else if (t.GetType() == typeof(int))
{
return (T)Convert.ChangeType(0, typeof(int));
}
}
return (T)Convert.ChangeType(null, typeof(string));
}
and when calling it I type the following:
string typeName = wt.CheckParameterAndFetch(BuiltInParameter.ALL_MODEL_TYPE_NAME,typeof(string));
and I get this exception:
The type arguments for method 'namespace.Extensions.CheckParameterAndFetch (Autodesk.Revit.DB.Element, Autodesk.Revit.DB.BuiltInParameter, System.Type)' cannot be inferred from the usage. Try specifying the type arguments explicitly. (CS0411)
Upvotes: 1
Views: 2993
Reputation: 3716
I think that with the latest .NET framework you can just call it like so: var param = v.get_Parameter(BuiltInParameter.ALL_MODEL_COST)?.AsInteger();
notice the '?' after the get_Parameter()
call. That checks whether the parameter returned was null
and will not call AsInteger()
if it was null
. Here's some more info:
Upvotes: 1