AllowRankReductionAttribute
This attribute can be applied to methods that return collection of
objects, but with some combination of input parameters it returns a
collection of single object and at designscript side we want the method
to return a single object instead of a collection of single object.
using System;
using System.Collections;
namespace Autodesk.DesignScript.Runtime
{
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Property)]
public sealed class AllowRankReductionAttribute : Attribute
{
public object ReduceRank(object collection)
{
if (collection == null)
return null;
Type type = collection.GetType();
if (type.IsArray) {
Array array = collection as Array;
if (array != null && array.Length == 1)
return array.GetValue(0);
} else if (typeof(IEnumerable).IsAssignableFrom(type)) {
IEnumerable enumerable = collection as IEnumerable;
if (enumerable != null) {
int num = 0;
object result = null;
foreach (object item in enumerable) {
num++;
if (num <= 1)
result = item;
else if (num > 1) {
break;
}
}
if (num == 1)
return result;
}
}
return collection;
}
public static bool IsRankReducible(object collection)
{
if (collection == null)
return false;
Type type = collection.GetType();
if (type.IsArray) {
Array array = collection as Array;
if (array != null && array.Length == 1)
return true;
} else if (typeof(IEnumerable).IsAssignableFrom(type)) {
IEnumerable enumerable = collection as IEnumerable;
if (enumerable != null) {
int num = 0;
foreach (object item in enumerable) {
num++;
if (num > 1)
return false;
}
if (num == 1)
return true;
}
}
return false;
}
}
}