Set Elements of Array to Same Value in C#

  • Thread starter Thread starter Sojourner01
  • Start date Start date
  • Tags Tags
    Arrays Stupid
Join the discussion
Registration is free. Ask a follow-up in this thread, or start your own.
3 replies · 3K views
Sojourner01
Messages
371
Reaction score
0
For some reason, I can't work out how to set every element of an array to the same value in a single line, in C#. For example, I can't do this:

char[] array_of_chars = new char[limit];
array of chars[] = X

or:

char[] array_of_chars = new char[limit];
array of chars[0:limit] = X

So how is it done? Can it be done, or do I have to iterate? If so, that's a very stupid omission from the language.
 
Physics news on Phys.org
There is the following shorthand, but it's not exactly what you describe:
Code:
char[] myChars = new char[]{'a', 'b', 'c', 'd', 'e', 'f', 'g'};
I think that's the best you can do in C# without iterating, i have not seen another way, perhaps you can hack something using Lambda expressions in .NET 3.0+, but probably nothing really worthwhile.

You can after all do:
Code:
char[] myChar = new char[100];
for(int i=0; i<myChar.length; i++){myChar[i] = 'X';}
That's one line, and you know any syntax in C# for initializing would be converted to the iteration form when compiling, so it's really non-essential, though admittedly it would be cleaner.
 
Last edited:
You can also create a class that wraps around an array or list that supports initialization, such as:
Code:
public class BetterArray<T> : List<T>{
    public BetterArray(T DefaultValue, int Length) : base(Length)
    {
        for (int i = 0; i < Length; i++)
        {
            this.Add(DefaultValue);
        }
    }
}
With usage:
Code:
BetterArray<char> myChars = new BetterArray<char>('X', 100);
foreach(char c in myChars){
    Console.WriteLine(c);
}
 
Thanks, in the end I iterated the initialisation. Listing every element in the declaration is unrealistic since there are on the order of hundreds of thousands of elements in the application.

I find the absence of a constant initialisation expression for arrays rather odd. Perhaps it was excluded intentionally to stop mistakes along the lines of accidentally initialising an array thinking it was a single variable?

Regardless, I'm going to have to rebuild the whole thing anyway since the initialisation logic elsewhere was irrevocably broken. More functions are the way forward, I think.