P
P
Pragma Games2022-02-12 15:46:07
C++ / C#
Pragma Games, 2022-02-12 15:46:07

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);


This code throws the error
ArgumentException: Object of type 'System.Object[]' cannot be converted to type 'TestScripts.Test4[]'.

How to solve such a problem without explicitly casting the array to the desired type?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2022-02-12
@PragmaGames

How to solve such a problem without explicitly casting the array to the desired type?

Hmm, how is this supposed to work? You have an array of objects, and you are waiting for an array of Classes.
You need a function that will convert each element individually, because this array will not necessarily contain Class.
Maybe it's easier to create an array of the desired type right away?
In general, there are several options:
1. Through Select and some function that converts the object to your type.
var classes = objects.Select(ConvertObjectToClass).ToArray();

2. Through the Cast method - then each element will simply be downcast.
var classes = objects.Cast<Class>().ToArray();
3. Through Unsafe, but only if you know in advance that only Classes are inside this array, and not some other types that are not compatible with it. Otherwise you will get garbage instead of data. With structures, of course, will not work.
var classes = System.Runtime.CompilerServices.Unsafe.As<Class[]>(objects);

Here's what will happen

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 question

Ask a Question

731 491 924 answers to any question