Click here to Skip to main content
15,883,623 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
I am trying to code an extension conversion operator for
System.Collections.Generic.Collection.

The purpose is to convert a collection of T1 types to a collection of T2 types.
I already defined the required set of conversions from T1 to T2.

XML
public static class CollectionExtension
    {
        public static explicit operator Collection<T2>(this Collection<T1> rhs)
            where T1 : class
            where T2 : class, new()
        {
            Collection<T2> lhs = new Collection<T2>();
            // Foreach ...
            return lhs;
        }
    }


I got as far as this by looking at existing posts, but it won't compile.
Could some one please explain how to do this.

Thanks.
Posted

The idea is simple: you should provide one more parameter (method parameter, not generic parameter): the delegate instance converting the element of the type T1 to the type T2. Your type constraints for T1 and T2 are absolutely redundant and useless. You can work with elements of any types, not just classes.

Your delegate-type parameter should itself be generic, using the same generic parameters, T1 and T2:
C#
public static class SomeExtensionUtility {

    public static List<T2> ConvertList<T1, T2>(
            this List<T1> list,
            System.Func<T1, T2> convertor) {
        return // please implement it yourself
    }

}


The implementation is simple: you convert elements in source collection to T2 add then to the target collection, one by one, in a loop. I replaced Collection with List just for example, because Collection is probably some your type which I don't have.

By the way, it is not quite clear why did you call your class CollectionExtension :-).
It won't work this way, because you operator, as the operator of the static class, won't compile. But my class can be used as the extension class.

[EDIT]

The usage of this extension method won't be different from any other extension method:

C#
using MyExtensionMethods; // let's assume this is the namespace with SomeExtensionUtility
// let me stay with System.Collections.Generic.List<>, just for example,
// it will be easier to demonstrate:
using System.Collections.Generic;

//...

List<string> stringList = new List<string>();
List<int> intList = stringList.ConvertList<string, int>(
    (stringValue) => { return int.Parse(stringValue); }
);


For some background, please also read:
http://en.wikipedia.org/wiki/Covariance_and_contravariance_%28computer_science%29[^],
http://msdn.microsoft.com/en-us/library/dd799517%28v=vs.110%29.aspx[^].

This covariance/contravariance matter is really non-trivial, but the problem and the solution I demonstrated are trivial enough.

—SA
 
Share this answer
 
v11
Comments
Member 10167731 19-Mar-14 14:16pm    
Thanks for your response. Now I just have to figure out how to call this.

BTW: The Collection that I am referring to is the .NET System.Collections.ObjectModel.Collection class.
That is also the reason why I called my class CollectionExtension
since this explicit conversion operator is meant to implement a new method for that Collection class.

Thanks again for your help.
Sergey Alexandrovich Kryukov 19-Mar-14 15:13pm    
I would not advise to use System.Collections.ObjectModel.Collection unless it is really required by the code using it (say, using ObjectModel itself).
But anyway, if you use it, my solution will work the same way.
You can use this method exactly in the same way as any other extension method. What's the problem?
—SA
Sergey Alexandrovich Kryukov 19-Mar-14 15:33pm    
Anyway, I answered; please see the update to the answer, after [EDIT].

Will you accept the answer formally now (green "Accept" button")?
It's unclear why did you accept derived Solution 2 and did not accept my solution, which is original. You can accept both if you want, but accepting just Solution 2 is just wrong.
Bill also suggested you to accept Solution 1.

—SA
Member 10167731 19-Mar-14 16:04pm    
I did accepted both solutions.
Sergey Alexandrovich Kryukov 19-Mar-14 16:25pm    
Very good.
Good luck, call again.
—SA
I think Sergey "got there" first, and gave you the key insight you need; I suggest you accept his answer.

While I am not familiar with the ObjectModel.Collection class, I have written an extension method to convert a Generic List of one Type to a Generic List of another Type:
C#
public static class GenericListExtensions
{
    public static List<T2> ConvertGenericList<T1, T2>(this List<T1> T1List, Func<T1,T2> conversionFunc)
    {
        return T1List.Select(conversionFunc).ToList();
    }
}
An example of usage:
C#
List<int> intList = new List<int>{1,2,3,4,5};

List<string> stringList = intList.ConvertGenericList<int, string>(anInt => anInt.ToString());
Linq and Lambda really allow some useful brevity !
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 19-Mar-14 23:29pm    
I gladly up-vote this one. I explained in my comment what it is. You added the example of usage before I added it to my solution, in response to OP's concern about the usage, specifically. These "priority" issues are really meaningless because we are not contribute anything new here.

Best wishes.
—SA

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900