0

I had a real scenario 5 minutes ago where I needed to turn a Guid[] into an object[].

The dead simple and quick way out of this is to type:

var dataset = inputArray.Select(item => (object)item).ToArray();

Readable and everything, but I'm not sure it is very effective (could of course be the case that the compiler optimizes it a bit).

What would you suggest is best to go from type to type (assuming it is castable between, skipping integer parsing and the like)?

EDIT: Cast<T> extension method is of course also usable.

var listOfGuids = new Guid[]{Guid.NewGuid(), Guid.NewGuid(), Guid.NewGuid()};
var listOfStrings = new string[]{"foo", "bar"};

var objectListGuidsLinq = listOfGuids.Cast<object>().ToArray();
var objectListStringsLinq = listOfStrings.Cast<object>().ToArray();
var objectListStringsDirect = (object[]) listOfStrings;
krembanan
  • 1,408
  • 12
  • 28

2 Answers2

3

In the case of an array of value types they need to be boxed, so your method or something similar like inputArray.Cast<object>().ToArray() is required.

However, an array of reference types can be implicitly cast to object[].

Also the OfType extension method is useful for filtering when you have an array of multiple types.

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
  • Guid is not considered a reference type, so for the example the array cannot be implicitly cast to object[]. I guess for value types the most efficient way is to use Select or Cast<> linq methods. – krembanan Aug 01 '12 at 08:37
  • Yes, I forgot to mention, Guid is a value type. Also, there are the `Array.CopyTo` and `Array.Copy` methods but I did a quick benchmark and didn't see any significant difference in performance over the Linq methods. – Mike Zboray Aug 01 '12 at 09:02
0

i am thinking you are doing it correct. please check this : IEnumerable.Cast<>

it seems that Cast method dose note work as you expect from its name.

Community
  • 1
  • 1
Behnam Esmaili
  • 5,835
  • 6
  • 32
  • 63