The short version -
Is there an easy way to take a variable of type object containing an instance of an unknown array (UInt16[], string[], etc.) and treat it as an array, say call String.Join(",", obj) to produce a comma delimited string?
Trivial? I thought so too.
Consider the following:
object obj = properties.Current.Value;
obj might contain different instances - an array for example, say UInt16[], string[], etc.
I want to treat obj as the type that it is, namely - perform a cast to an unknown type. After I accomplish that, I will be able to continue normally, namely:
Type objType = obj.GetType();
string output = String.Join(",", (objType)obj);
The above code, of course, does not work (objType unknown).
Neither does this:
object[] objArr = (object[])obj; (Unable to cast exception)
Just to be clear - I am not trying to convert the object to an array (it's already an instance of an array), just be able to treat it as one.
Thank you.
No, you can just create a new array and cast your objects one by one. In Java, arrays are hardly ever the way to go, though. You can, sort of, "cast" Object[] to DataObject[] using System. arraycopy.
It only works for arrays of reference types. Arrays of value types are a physically different size, so this cannot work.
The Array type casting method is used to convert a single value from integer, float, string, boolean data types into an array. The first element’s index always will be 0, and the total count of an array is 1. Please find below the examples,
Explicit C++ type Casting: The word “explicit” means ‘open’ or ‘clear’. In explicit C++ type casting, the data type in which the value is to be converted is clearly specified in the program. It is done by cast operator.
In Smart Casting, we generally use is or !is operator to check the type of variable, and compiler automatically casts the variable to the target type, but in explicit type casting we use as operator. Explicit type casting can be done using : Safe cast operator: as?
Type casting are of two types they are Automatic type conversion can happen if both type are compatible and target type is larger than source type. No Explicit casting required for the above mentioned sequence.
Assuming you're using .NET 4 (where string.Join
gained more overloads) or later there are two simple options:
Use dynamic typing to get the compiler to work out the generic type argument:
dynamic obj = properties.Current.Value;
string output = string.Join(",", obj);
Cast to IEnumerable
, then use Cast<object>
to get an IEnumerable<object>
:
IEnumerable obj = (IEnumerable) properties.Current.Value;
string output = string.Join(",", obj.Cast<object>());
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