Skip to content

Instantly share code, notes, and snippets.

@gregseth
Created February 18, 2013 12:48
Show Gist options
  • Save gregseth/4977131 to your computer and use it in GitHub Desktop.
Save gregseth/4977131 to your computer and use it in GitHub Desktop.
Boxing and unboxing of arrays (.NET 4)
class Util
{
public static Array GetArrayAs(Type t_, Array array_)
{
int iDimensions = array_.Rank;
int[] iSizes = new int[iDimensions];
int iCount = array.Length;
for (int i=0; i<iDimensions; ++i)
{
iSizes[i] = array.GetLength(i);
}
var aArray = Array.CreateInstance(t_, iSizes);
int[] iIndexes = new int[iDimensions];
for (int i=0; i<iCount; ++i)
{
int iDivider = 1;
for (int j=0; j<iDimensions; ++j)
{
iIndexes[j] = i / iDivider % iSizes[j];
iDivider *= iSizes[j];
}
aArray.SetValue(array_.GetValue(iIndexes), iIndexes);
}
return aArray;
}
public static dynamic Unbox(object o_)
{
dynamic dUnboxed = o_;
if (o_.GetType().IsArray)
{
Array array = (Array)o_;
bool bIsEmpty = true;
bool bHasNullElement = false;
bool bHasHomogenousType = true;
Type type = null;
foreach (object item in array)
{
bIsEmpty = false;
if (item == null)
{
bHasNullElement = true;
break;
}
else
{
if (type == null)
{
type = item.GetType();
}
else if (type != item.GetType())
{
bHasHomogenousType = false;
break;
}
}
}
if (!bIsEmpty && !bHasNullElement && bHasHomogenousType)
{
dUnboxed = GetArrayAs(type, array);
}
else
{
dUnboxed = null;
}
}
return dUnboxed;
}
public static object Objection(object o_)
{
object oObjected = o_;
if (o_.GetType().IsArray)
{
oObjected = GetArrayAs(typeof(object), (Array)o);
}
return oObjected;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment