Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Stupid arrays question

  1. Dec 9, 2007 #1
    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.
     
  2. jcsd
  3. Dec 9, 2007 #2

    -Job-

    User Avatar
    Science Advisor

    There is the following shorthand, but it's not exactly what you describe:
    Code (Text):

    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 (Text):

    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: Dec 9, 2007
  4. Dec 9, 2007 #3

    -Job-

    User Avatar
    Science Advisor

    You can also create a class that wraps around an array or list that supports initialization, such as:
    Code (Text):

    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 (Text):

    BetterArray<char> myChars = new BetterArray<char>('X', 100);
    foreach(char c in myChars){
        Console.WriteLine(c);
    }
     
     
  5. Dec 11, 2007 #4
    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.
     
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook

Have something to add?



Similar Discussions: Stupid arrays question
Loading...