Invalid implementation of IEnumerable to set with IEnumerable

I am trying to create a custom type that implements IEnumerable<T>

as I need a custom type converter. I currently have this:

[TypeConverter(typeof(StringListTypeConverter))]
public class StringList<T> : IEnumerable<T>, IStringConvertible
{
    // ... implementations of IEnumerable<T>
}

      

However, when I change my old property types from IEnumerable<string> MyProp

to StringList<T> MyProp

, I get errors when these properties are set eg.

MyProp = new[]{"test"};
MyProp = SomeListArray.Select(s => $"{s}_test");

      

I am getting the error:

'System.String []' to 'StringList <String>'

'System.Collections.Generic.IEnumerable <String>' to 'StringList <String>'. Explicit conversion exists (are you missing the listing?)

Pay attention to the questions from the comment. I want to pass IEnumerable

type T

through QueryString

to my api server. To keep the URL as short as possible, I only want by parameter ?MyProp=test,anotherstring,evenMoreString&MyIntProp=1,4,12,134

. On the server side, I want to convert this string back to IEnumerable<T>

(in the case of the example QueryString

to IEnumerable<string>

and IEnumerable<int>

).

I have already tried to add the implicit operator

public static implicit operator StringList<T>(IEnumerable<T> elements)
{
    return new StringList<T>(elements);
}

      

but this is prohibited by the C # specs. So what can I do to change the type of the property instead of all the code where they are set (since this is a pretty big refactoring)?

+3


source to share


1 answer


MyProp = new [] {"test"};

If your type is a property MyProp

StringList<T>

, you cannot assign an array instance to it because an array is not derived from it.

MyProp = SomeListArray.Select (s => $ "{s} _test");



Almost the same. LINQ returns IEnumerable, which is not the result of StringList. You cannot assign an object of a base type to a variable of a derived type.

You can add an extension method and use it when you need an object StringList<T>

:

public static class StringListExtensions
{
    public static StringList<T> ToStringList<T>(this IEnumerable<T> elements)
    {
        return new StringList<T>();
    }
}

MyProp = SomeListArray.Select(s => $"{s}_test").ToStringList();

      

0


source







All Articles