I have an enum that has 4 values:
public enum DriveRates
{
driveSidereal = 0,
driveLunar = 1,
driveSolar = 2,
driveKing = 3
}
I have an array of values that I want to cast to an array of DriveRates. However when I do var rates = (DriveRates[])ret;
, with ret
being an object array of numbers (probably integers), it says Unable to cast object of type 'System.Object[]' to type 'ASCOM.DeviceInterface.DriveRates[]'.
ret
={0,1,2,3}
. How should I do this instead. Again, I am trying to convert an array of enum values to an array of enum...well, values :) But I'm trying to convert from type object[]
to type DriveRates[]
.
In C++, I can define a enum and use the enum as the array index.
You can iterate through an enum to access its values. The static values() method of the java. lang. Enum class that all enums inherit gives you an array of enum values.
Array is a value and enum is a type. array is a collection of different values whereas enum value is simply one value. Array is used to iterate among various values using index whereas enum is assigned some atomic value and iterated so that we can easily iterate the type.
Enums are value types (usually Int32). Like any integer value, you can access an array with their values. Enum values are ordered starting with zero, based on their textual order. MessageType We see the MessageType enum, which is a series of int values you can access with strongly-typed named constants.
You can't just cast the array, if it's really an object[]
. You can create a new array pretty easily though:
var enumArray = originalArray.Cast<DriveRates>().ToArray();
If it were actually an int[]
array to start with, you could cast - although you'd have to talk nicely to the C# compiler first:
using System;
class Program
{
enum Foo
{
Bar = 1,
Baz = 2
}
static void Main()
{
int[] ints = new int[] { 1, 2 };
Foo[] foos = (Foo[]) (object) ints;
foreach (var foo in foos)
{
Console.WriteLine(foo);
}
}
}
The C# compiler doesn't believe that there's a conversion from int[]
to Foo[]
(and there isn't, within the rules of C#)... but the CLR is fine with this conversion, so as long as you can persuade the C# compiler to play along (by casting to object
first) it's fine.
This doesn't work when the original array is really an object[]
though.
This isn't possible. There is no way to cast between an array of reference types and an array of value types. You will need to manually copy the elements into the new array
DriveRates[] Convert(object[] source) {
var dest = new DriveRates[source.Length];
for (int i = 0; i < source.Length; i++) {
dest[i] = (DriveRates)source[i];
}
return dest;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With