Probably the easiest, and most C#-idiomatic way to do this is to use the in-built function:
Enumerable.Repeat(charReplace, lengthOfArray);
If you specifically need this in an array rather than a general IEnumerable<char>
, you can simply add:
Enumerable.Repeat(charReplace, lengthOfArray).ToArray();
In C#, in general you should use these kinds of enumerable-manipulating methods (found in the System.Linq
namespace) instead of loops as your first port of call. They usually lead to terser, easier to read code. Only occasionally are loops easier to read.
Beyond this, I have to echo Heslacher on both the issues with naming and with this method mixing its responsibilities. In fact, these issues are linked, because taking care with your naming is often the best early-warning mechanism for a method doing too much, or lacking a single purpose.
For example, what should this method be called? GetInitializedArray
as Heslacher suggests is nice, but doesn't actually describe your initial method well, because it gives no indication that it's also going to be doing IO.
GetInitializedArrayFromConsoleInput
would be a more accurate name, and this should immediately raise alarm bells: Why is this description so long? Why does it combine two unrelated concepts (initializing an array and console IO)? The answer is that the method lacks a single purpose (or "responsibility"), and should be separated out.
lengthOfArray
and charReplace
are okay names, but not great. Both seem to put too much focus on the data-types involved. This method is simple enough that that's probably not a big problem, but in general your emphasis should be on what you're trying to do, not how you're trying to do it. I can't think of better names than length
and initialValue
from Heslacher's answer.