Answer the question
In order to leave comments, you need to log in
How to convert object[] to Class[] where Class is a custom class?
Hello. There is some code like this:
public void A(Class[] class)
{
TODO
}
------
var classes = new object[5];
A(classes);
Answer the question
In order to leave comments, you need to log in
How to solve such a problem without explicitly casting the array to the desired type?
var classes = objects.Select(ConvertObjectToClass).ToArray();
var classes = objects.Cast<Class>().ToArray();
var classes = System.Runtime.CompilerServices.Unsafe.As<Class[]>(objects);
using System.Runtime.CompilerServices;
var objects = new object[] { new A { x = 1 }, new B { y = 2, z = 3 } };
var something = Unsafe.As<A[]>(objects);
Console.WriteLine(something[0].x); // 1
Console.WriteLine(something[1].x); // 2
var something2 = Unsafe.As<B[]>(objects);
Console.WriteLine($"{something2[0].y} {something2[0].z}"); // 1 0
Console.WriteLine($"{something2[1].y} {something2[1].z}"); // 2 3
class A
{
public int x;
}
class B
{
public int y;
public int z;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question