Search code examples
c#arraysunity-game-enginecode-translation

Create array class objects


I want to do something that I've done before in Java, but need to do in C#.

The code in Java that do would be similar to:

public Class<? extends Thing>[] classes = new Class<? extends Thing>[3] {
    OneThing.class,
    AnotherThing.class
    YetAnotherThing.class
    // etc.
}

Is this possible in C# in any way? Ultimately what I'm trying to do is to have an array of classes representing types of items. Then this array is used to check against the type of the item to produce a boolean value representing if the item has a superclass of the index in the array. To clarify, I'm checking to see if the class of the instance of a Thing is also an instance of OneThing, AnotherThing, etc.

What matters is that I'm trying to create an array not of a regular object like Random, but of whatever C#'s counterpart of the Java Class class is.


Solution

  • Unlike Java where Class<T> is generic on the type represented by the class, System.Type objects of C# are not generic at all. You can create an array of them as follows:

    Type[] classes = new[] {
        typeof(OneThing)
    ,   typeof(AnotherThing)
    ,   typeof(ThirdThing)
    };
    

    However, the compiler is unable to enforce the check that the classes derive from or implement a particular base or an interface. You should be able to perform your checks without this restriction, though:

    var obj = ... // This is your object
    var res = classes.Select((t, i) => new {t, i}).FirstOrDefault(p => p.t.IsAssignableFrom(typeof(obj)));
    if (res != 0) {
        Console.WriteLine("{0} assignable from {1} is found at {2}.", res.t, typeof(obj), res.i);
    } else {
        Console.WriteLine("Type {0} is not found in the array.", typeof(obj));
    }