Search code examples
c#naudio

Foreach statement cannot operate on variables of type "?"


I have the following piece of code:

using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
{
    using (var sessionEnumerator = sessionManager.GetSessionEnumerator())
    {
        foreach (var session in sessionEnumerator)
        {
         //Code
        }
    }
}

But I get an error saying

Foreach statement cannot operate on variables of type "?"

How can I fix this problem?


Solution

  • as the name implies sessionEnumerator is an IEnumerator but foreach requires IEnumerable. here is the alternative of foreach statement.

    using (var sessionManager = GetDefaultAudioSessionManager2(DataFlow.Render))
    {
        while(sessionEnumerator.MoveNext())
        {
            var session = sessionEnumerator.Current;
    
            // Code
        }
    }