Search code examples
c#ienumerableyield-return

In C# how can a function have an IEnumerable Interface as a return type?


So I understand that this function allows the result to be iterated over with a foreach statement, but I don't understand how the return type can be an interface.

public static IEnumerable<int> Func1(int number, int exponent)
{
    int exponentNum = 0;
    int numberResult = 1;

    while (exponentNum < exponent)
    {
        numberResult *= number;
        exponentNum++;

        yield return numberResult;
    }
}

On the MSDN documentation it states:

The interface defines only the signature

• An interface can't be instantiated directly. Its members are implemented by any class or struct that implements the interface.

So if Interfaces contain only method signatures, then how can one possibly be the return type of a function? and how does this function enable the foreach statement?


Solution

  • It means that you can return anything that implements the interface, and the calling code need not care what the concrete implementation is, but it can use any of the functions of the returned object that are declared in the interface.

    It's one way that you have of creating standard interfaces between parts of your code, while allowing the internal implementation to be changed without affecting everything else.

    So for instance you could return a List<int> from your function, and it would be valid.

    Your function uses yield return, which means it will return each element of the iteration one at a time and implicitly create the IEnumerable<int> for you, rather than you creating an explicit list object. Internally it will create some concrete type that implements IEnumerable and return that, but the calling code will just see it as an IEnumerable because that's the return type of the method. https://msdn.microsoft.com/en-us/library/9k7k7cf0.aspx gives you more details and also an example very similar to the function you've posted.