Why does this extension method not work?

I can’t do what I want. I only want accounts for non-international representatives. But when I call ActiveAccounts (), I don't get null, I get an enumerated one that then includes null. What am I doing wrong here? Help me please.

public static class AccountExt
{
    public static IEnumerable<Account> ActiveAccounts( this AccountRep rep )
    {
        if( rep == null )
            throw new ArgumentNullException();
        if( rep.IsInternational )
            yield return null;

        foreach( var acc in rep.FetchAccounts() )
        {
            if( acc.IsActive )
                yield return acc;
        }
    }
}
+3
source share
2 answers

Well, there are a few things.

Firstly, you do not just have an extension method , you have an iterator block extension method - what you get when you use a yield returncontract for automatic implementation IEnumerable<>.

, , ActiveAccounts() null IEnumerable<Account>. , , null IEnumerable. , return null , :

: . .

, , yield break yield return null. , , , , . , LINQ, .

, if( rep == null ) ActiveAccounts(), . , , - , , .

:

public static class AccountExt
{
   // apply preconditions, return null for international reps
   public static IEnumerable<Account> ActiveAccounts( this AccountRep rep )
   {
       if( rep == null )
           throw new ArgumentNullException( "rep" );
       if( rep.IsInternational )
           return null;
       // otherwise...
       return ActiveAccountsImpl( rep );
   }

   // private implementation handles returning active accounts
   private static IEnumerable<Account> ActiveAccountsImpl( AccountRep rep )
   {
       foreach( acc in rep.FetchAccounts() )
       {
           if( acc.IsActive )
               yield return acc;
       }
   }
}

LINQ, Impl :

   public static IEnumerable<Account> ActiveAccounts( this AccountRep rep )
   {
       if( rep == null )
           throw new ArgumentNullException( "rep" );
       if( rep.IsInternational )
           return null;
       // otherwise, using LINQ to filter the accounts...
       return rep.FetchAccounts().Where( acc => acc.IsActive );
   }

, .

+8

yield return null yield break. .

null IEnumerable, LBushkin - , ; , .

+5

Source: https://habr.com/ru/post/1732449/


All Articles