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

Time:10-15

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
}

CodePudding user response:

Sounds like all you need is Enumerable.Repeat:

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

public class Generator : IBoolS
{
    public bool ValueToGenerate { get; set; }

    public IEnumerable<bool> GetBools(int N) => Enumerable.Repeat(ValueToGenerate, N);
}

CodePudding user response:

Here's a possible implementation (not a performant one though):

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

public class Generator : IBoolS
{
    private bool _valueToGenerate;
    
    public Generator(bool valueToGenerate) {
        _valueToGenerate = valueToGenerate;
    }

    public IEnumerable<bool> GetBools(int N) {
        foreach (var n in Enumerable.Range(0, N)) {
            yield return _valueToGenerate;
        }                        
    }
}

CodePudding user response:

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; 
    } 
} 
  • Related