Search code examples
c#.netienumerableyield-return

How would I return N number of IEnumerable<bool> value with a single method in C#?


Task:

  • Create a public interface called IBoolS with a single method called GetBools: Parameter int N, return value IEnumerable .

  • Create a public class called Generator that implements this interface with a boolean property called ValueToGenerate, and the GetBools method here should return N pieces of ValueToGenerate.

This is what I've tried so far:

IBoolS.cs:

public interface IBoolS
{
   public IEnumerable<bool> GetBools(int N)
    {
        //what goes here? yield return something, but what?
    }
}

Generator.cs:

public class Generator : IBoolS
{
    private bool ValueToGenerate;

    //GetBools(N pieces of ValueToGenerate);, but should be an integer number
}

Solution

  • Interface is just a declaration, a contract for the class(es) which implement it:

    public interface IBoolS
    {
       IEnumerable<bool> GetBools(int N);
    }
    

    class implements the interface:

    public class Generator : IBoolS
    {
        // Let's have a property instead of field: which value is generated
        public bool ValueToGenerate {get;}
    
        // Do not forget a constructor - we have to set ValueToGenerate
        public Generator(bool valueToGenerate) {
          ValueToGenerate = valueToGenerate;
        }    
    
        // Interface implementation: we generate N bool values
        public IEnumerable<bool> GetBools(int N) {
          // Input validation
          if (N < 0)
            throw new ArgumentOutOfRangeException(nameof(N));
    
          // Shorter version is
          // return Enumerable.Repeat(ValueToGenerate, N);
          for (int i = 0; i < N; ++i)
            yield return ValueToGenerate; 
        } 
    }