Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yield to a IList return type

I have to realize a serializazion/deserialization class and i'm using System.Xml.Serialization. I have some IList<Decimal> type properties and wanted to serialize in IList<string> decoding all decimal value belonging to the list with a specific culture info. For example 10 is 10,00 with Italian culture info but 10.00 with English culture info. I tried to do it using this:

public IList<string> method()
    {
        for (int i = 0; i < 1000; i++)
        {
            yield return i.ToString();
        }
    }   

But i get at compile time Error 33

The body of 'Class1.method()' cannot be an iterator block because 'System.Collections.Generic.IList<string>' is not an iterator interface type

If i use as property type IEnumerable<string> it works succesfully but obviusly i can't change the type of data i want to serialize .

Any help is appreciated.

like image 540
Riccardo Avatar asked Jan 14 '23 22:01

Riccardo


1 Answers

yield only works with IEnumerable<T>, IEnumerable, IEnumerator<T> and IEnumerator as return type.
In your case, you need to use a normal method instead:

public IList<string> method()
{
    var result = new List<string>();
    for (int i = 0; i < 1000; i++)
    {
        result.Add(i.ToString());
    }
    return result;
}

Think about it. Your code would allow you to write the following code:

method().Add("foo");

That doesn't make too much sense, does it?

like image 139
Daniel Hilgarth Avatar answered Jan 26 '23 04:01

Daniel Hilgarth