patterncsharpMinor
Setting every element in an array to a given value
Viewed 0 times
arrayeveryvaluesettingelementgiven
Problem
Given the length of an array and a char, I would like to replace every element in a
Using a
char array with that given char.Using a
for loop, I'm changing each element to that char. Is there a better way to do it, or a specific method for that?using System;
using System.Collections.Generic;
namespace TestProject
{
class Solution
{
static void TestMethod()
{
//lines of code
int lengthOfArray = int.Parse(Console.ReadKey());
char charReplace = Console.ReadKey().KeyChar;
char[] arrayChar = new char[lengthOfArray];
for (int i = 0; i < lengthOfArray; i++)
{
arrayChar[i] = charReplace;
}
}
}
}Solution
You can also use the static
This will set all items in the array to
As mentioned in the comments by Pieter Witvoet, this feature is available in .NET Core only.
Array.Fill to quickly initialize an array to a given value:bool[] isPrime = new bool[500];
Array.Fill(isPrime, true);This will set all items in the array to
true.As mentioned in the comments by Pieter Witvoet, this feature is available in .NET Core only.
Code Snippets
bool[] isPrime = new bool[500];
Array.Fill(isPrime, true);Context
StackExchange Code Review Q#79058, answer score: 7
Revisions (0)
No revisions yet.