Implicit Type Conversions in Reflection

Posted by bradhe on Stack Overflow See other posts from Stack Overflow or by bradhe
Published on 2010-05-11T03:26:12Z Indexed on 2010/05/11 3:34 UTC
Read the original article Hit count: 239

Filed under:
|

So I've written a quick bit of code to help quickly convert between business objects and view models. Not to pimp my own blog, but you can find the details here if you're interested or need to know.

One issue I've run in to is that I have a custom collection type, ProductCollection, and I need to turn that in to a string[] in on my model. Obviously, since there is no default implicit cast, I'm getting an exception in my contract converter.

So, I thought I would write the next little bit of code and that should solve the problem:

public static implicit operator string[](ProductCollection collection) {
    var list = new List<string>();
    foreach (var product in collection)
    {
        if (product.Id == null)
        {
            list.Add(null);
        }
        else
        {
            list.Add(product.Id.ToString());
        }
    }
    return list.ToArray();
}

However, it still fails with the same cast exception. I'm wondering if it has something to do with being in reflection? If so, is there anything that I can do here?? I'm open to architectural solutions, too!

© Stack Overflow or respective owner

Related posts about c#

Related posts about casting