views:

6150

answers:

6

Scenario:

I'm currently writing a layer to abstract 3 similar webservices into one useable class. Each webservice exposes a set of objects that share commonality. I have created a set of intermediary objects which exploit the commonality. However in my layer I need to convert between the web service objects and my objects.

I've used reflection to create the appropriate type at run time before I make the call to the web service like so:

    public static object[] CreateProperties(Type type, IProperty[] properties)
    {
        //Empty so return null
        if (properties==null || properties.Length == 0)
            return null;

        //Check the type is allowed
        CheckPropertyTypes("CreateProperties(Type,IProperty[])",type);

        //Convert the array of intermediary IProperty objects into
        // the passed service type e.g. Service1.Property
        object[] result = new object[properties.Length];
        for (int i = 0; i < properties.Length; i++)
        {
            IProperty fromProp = properties[i];
            object toProp = ReflectionUtility.CreateInstance(type, null);
            ServiceUtils.CopyProperties(fromProp, toProp);
            result[i] = toProp;
        }
        return result;
    }

Here's my calling code, from one of my service implementations:

Property[] props = (Property[])ObjectFactory.CreateProperties(typeof(Property), properties);
_service.SetProperties(folderItem.Path, props);

So each service exposes a different "Property" object which I hide behind my own implementation of my IProperty interface.

The reflection code works in unit tests producing an array of objects whose elements are of the appropriate type. But the calling code fails:

System.InvalidCastException: Unable to cast object of type 'System.Object[]' to type 'MyProject.Property[]

Any ideas?

I was under the impression that any cast from Object will work as long as the contained object is convertable?

+3  A: 

You can't convert an array like that - it's returning an array of objects, which is different from an object. Try Array.ConvertAll

Tom Ritter
+1  A: 

That's correct, but that doesn't mean that you can cast containers of type Object to containers of other types. An Object[] is not the same thing as an Object (though you, strangely, could cast Object[] to Object).

DannySmurf
Well, to be pedantic, and Object[] *is* an Object... so the cast isn't that strange. Everything is an Object in .NET
Marc Gravell
+6  A: 

Basically, no. There are a few, limited, uses of array covariance, but it is better to simply know which type of array you want. There is a generic Array.ConvertAll that is easy enough (at least, it is easier with C# 3.0):

Property[] props = Array.ConvertAll(source, prop => (Property)prop);

The C# 2.0 version (identical in meaning) is much less eyeball-friendly:

 Property[] props = Array.ConvertAll<object,Property>(
     source, delegate(object prop) { return (Property)prop; });

Or just create a new Property[] of the right size and copy manually (or via Array.Copy).

As an example of the things you can do with array covariance:

Property[] props = new Property[2];
props[0] = new Property();
props[1] = new Property();

object[] asObj = (object[])props;

Here, "asObj" is still a Property[] - it it simply accessible as object[]. In C# 2.0 and above, generics usually make a better option than array covariance.

Marc Gravell
Thanks, this works. What's the performance impact of convertall vs. copy?
Rob Stevenson-Leggett
ConvertAll will involve a delegate invoke each time, where-as Copy should just use Buffer.BlockCopy under the hoop. So Copy should be quicker. ConvertAll is easier to type (and fine for small-to-mid sizes), and more flexible: you can do non-trivial projections.
Marc Gravell
Also - ConvertAll will cope with conversions rather than casts; Array.Copy can't do this, as there is no guarantee that the original and destination objects are the same size (which is necessary for Buffer.BlockCopy)
Marc Gravell
+3  A: 

As others have said, the array has to be of the right type to start with. The other answers have shown how to convert a genuine object[] after the fact, but you can create the right kind of array to start with using Array.CreateInstance:

object[] result = (object[]) Array.CreateInstance(type, properties.Length);

Assuming type is a reference type, this should work - the array will be of the correct type, but you'll use it as an object[] just to populate it.

Jon Skeet
So many times I just fall into this trap with valuetypes, then I remember :)
leppie
Great info! thanks, StackOverflow needs assisted answers.It would be nice to know the type but I'm trying to write as little code as possible. This way I can add more services later without having to write the mapping code again. I would have to write 3 loops in 3 methods currently.
Rob Stevenson-Leggett
Rob: You're already passing in the type as a parameter to the method, aren't you? Have I misunderstood something?
Jon Skeet
Yeah... don't know what I was talking about here!
Rob Stevenson-Leggett
+5  A: 

Alternative answer: generics.

public static T[] CreateProperties<T>(IProperty[] properties)
    where T : class, new()
{
    //Empty so return null
    if (properties==null || properties.Length == 0)
        return null;

    //Check the type is allowed
    CheckPropertyTypes("CreateProperties(Type,IProperty[])",typeof(T));

    //Convert the array of intermediary IProperty objects into
    // the passed service type e.g. Service1.Property
    T[] result = new T[properties.Length];
    for (int i = 0; i < properties.Length; i++)
    {
        T[i] = new T();
        ServiceUtils.CopyProperties(properties[i], t[i]);
    }
    return result;
}

Then your calling code becomes:

Property[] props = ObjectFactory.CreateProperties<Property>(properties);
_service.SetProperties(folderItem.Path, props);

Much cleaner :)

Jon Skeet
Well, I did say " In C# 2.0 and above, generics usually make a better option than array covariance.". I'm afraid I had to cancel my +1 on your last post to +1 this... I'm all out for today...
Marc Gravell
Arguably, it returns something a little dodgy for the Length==0 case - I'd return an empty array myself...
Marc Gravell
Edited to remove accusation :) And yes, returning null is possibly a bit dodgy - but that's a matter for the OP to decide :)
Jon Skeet
lol - no accusation taken; I kinda agreed with the original version ;-p
Marc Gravell
This is a much better solution, so switching answer (sorry Marc!).
Rob Stevenson-Leggett
A: 

in C# 2.0 you can do this using reflection, without using generics and without knowing the desired type at compile time.

//get the data from the object factory
object[] newDataArray = AppObjectFactory.BuildInstances(Type.GetType("OutputData"));
if (newDataArray != null)
{
    SomeComplexObject result = new SomeComplexObject();
    //find the source
    Type resultTypeRef = result.GetType();
    //get a reference to the property
    PropertyInfo pi = resultTypeRef.GetProperty("TargetPropertyName");
    if (pi != null)
    {
        //create an array of the correct type with the correct number of items
        pi.SetValue(result, Array.CreateInstance(Type.GetType("OutputData"), newDataArray.Length), null);
        //copy the data and leverage Array.Copy's built in type casting
        Array.Copy(newDataArray, pi.GetValue(result, null) as Array, newDataArray.Length);
    }
}

You would want to replace all the Type.GetType("OutputData") calls and the GetProperty("PropertyName") with some code that reads from a config file.

I would also use a generic to dictate the creation of SomeComplexObject

T result = new T();
Type resultTypeRef = result.GetType();

But I said you didn't need to use generics.

No guarantees on performance/efficiency, but it does work.

Mr. Graves