Search code examples
c#c++arraysfillequivalent

What is C# Equivalent to C++ STL fill method


In C++, we can set a range of values of an array(and other similar containers) using fill.

For example,

fill(number, number+n,10);

The above code will set the first n values of the array number with the value 10.

What is the closest C# equivalent to this.


Solution

  • There's no equivalent method but there are many ways to write similar code

    Methods from the Linq-to-Objects classes can create sequences that you can use to initialize lists but this is very different from how things in C++ actually occur.

    new List<char>(Enumerable.Repeat('A', 10));
    new List<int>(Enumerable.Range(1, 10));
    

    C++ can accomplish these things more generally thanks to how C++ templates work, and while simple type constraints in C# help, they do not offer the same flexibility.