Robin King
Robin King

Reputation: 387

How can I make a generic class convertible in type?

If I have a generic class:

class Collection < G >  {
    public G[] stuff
}

and I have two other classes, one of which can convert to the other (though more complex than this!)

class Foo {
    public Foo( int i ) { myInt = i; }
    public int myInt;
}
class Bar {
    public Bar( float f ) { myFloat = f; }
    public float myFloat;
    public static implicit operator Foo( Bar bar ) {
        return new Foo( Math.Ceil(bar.myFloat) );
    }
}

And I have collections of both:

Collection < G >  fooCollection = new Collection < Foo > ();
Collection < G >  barCollection = new Collection < Bar > ();

I want to be able to do something like this:

Collection < G > fooCollection2 = barCollection.Convert( typeof(Foo) );

How would I go about that?

EDIT: this is for Unity, which I believe is still on .NET 2.0.

Upvotes: 2

Views: 1228

Answers (1)

eulerfx
eulerfx

Reputation: 37739

Collection<Foo> fooCollection = new Collection<Foo> { stuff = barCollection.stuff.Select(bar => (Foo)bar).ToArray() };

If you'd like, you can add extension method to Collection:

public static Collection<TResult> Select<TResult, T>(this Collection<T> c, Func<T, TResult> projection)
{
   return new Collection<TResult> { stuff = c.stuff.Select(x => projection(x)).ToArray() };
}

And then you can call it like so:

Collection<Foo> fooCollection2 = barCollection.Select(bar => (Foo)bar);

Upvotes: 3

Related Questions