How to initialize an array through generics?

Is there a way to initialize all elements of an array to a constant value through generics?

-------------Problems Reply------------

I would use an extender (.net 3.5 feature)

public static class Extenders
public static T[] FillWith<T>( this T[] array, T value )
for(int i = 0; i < array.Length; i++)
array[i] = value;
return array;

// now you can do this...
int[] array = new int[100];
array.FillWith( 42 );

Personally, I would use a good, old for loop, but if you want a one-liner, here it is:

T[] array = Enumerable.Repeat(yourConstValue, 100).ToArray();

If you need to do this often, you can easily write a static method:

public static T[] FilledArray<T>(T value, int count)
T[] ret = new T[count];
for (int i=0; i < count; i++)
ret[i] = value;
return ret;

The nice thing about this is you get type inference:

string[] foos = FilledArray("foo", 100);

This is more efficient than the (otherwise neat) Enumerable.Repeat(...).ToArray() answer. The difference won't be much in small cases, but could be significant for larger counts.

Category:c# Views:1 Time:2009-01-23
Tags: c# generics

Related post

  • Initialize byte array from a portion of existing byte array c# 2010-04-12

    Is there are an easy way to initialize byte array from portion of existing byte array. In C language it is possible to use pointer to say like char s[10] = new char[10]; char* b = s + 5; Is it possible to do that in c#, like: byte[] b = new byte[buff

  • C++: constructor / initializer for array? 2011-03-07

    I'm familiar with C++ constructors & initializers: class Foo { int x; public: Foo(int _x) : x(_x) {} }; Foo foo1(37); Foo foo2(104); My question is that I have to implement a class that has a member which is a 3x6 array. How would I do something

  • 2D Arrays and Generics Issue (Java) 2011-11-25

    I'm having an issue understanding some compiler-errors, regarding 2D arrays (ArrayList containing an ArrayList) and generics. My understanding of generics isn't the best, so I tried to research the issue beforehand and still ended up confused. Accord

  • Initialize an array from XAML at runtime 2012-03-02

    I'd like to initialize an array from XAML in runtime, sort of like on Android. I've tried doing it like this: <ResourceDictionary xmlns="" xmlns:x="

  • Why can we use array with generic reference 2012-03-27

    While answering to a question about that here: I tried to do the following: Comparator<String>[] comparators = new Comparator[] {...}; It works! But the following doesn't: Comparator<String>[] comp

  • Making a 2D array of generic lists in Java 2012-03-31

    So - I want to make a 2D array of generic lists containing some data I am interested in (on a grid of of some set size), private ArrayList<MyDataStruct>[][] gridData; When I initialize this array, I go, gridData = (ArrayList<MyDataStruct>

  • How can I initialize an array of pointers to structs? 2008-10-11

    Is it possible to initialize an array of pointers to structs? Something like: struct country_t *countries[] = { {"United States of America", "America"}, {"England", "Europe"}, {"Ethiopia", "Africa"} } I want to do that in order to get the entities in

  • Initialize multidimensional array 2009-01-07

    Checkbox[,] checkArray = new Checkbox[2, 3]{{checkbox24,checkboxPref1,null}, {checkbox23,checkboxPref2,null}}; I am getting error . How do I initialize it? --------------Solutions------------- OK, I think I see what's happening here. You're trying to

  • What is the best way to initialize an array to a fixed-length array? (C++/CLI) 2009-01-29

    In managed C++/CLI, I could do this either as (1): array<System::Byte>^ css_keycode = {0x51, 0x67, 0x67, 0xc5, 0xe0, 0x00}; or (2): array<System::Byte>^ css_keycode; css_keycode = gcnew array<System::Byte>(6) {0x51, 0x67, 0x67, 0xc5

  • How to Initialize char array from a string 2009-06-08

    I want to do the following char a[] = { 'A', 'B', 'C', 'D'}; But I do not want to write these characters separately. I want something like #define S "ABCD" char a[] = { S[0], S[1], S[2], S[3] }; But this won't compile (gcc says 'initializer element i

  • Is there a way to initialize an array with non-constant variables? (C++) 2009-06-09

    I am trying to create a class as such: class CLASS { public: //stuff private: int x, y; char array[x][y]; }; Of course, it doesn't work until I change int x, y; to const static int x = 10, y = 10; Which is impractical, because I am trying to read the

  • How do you initialize an array in C#? 2009-08-06

    How do you initialize an array in C#? --------------Solutions------------- Like this: int[] values = new int[] { 1, 2, 3 }; or this: int[] values = new int[3]; values[0] = 1; values[1] = 2; values[2] = 3; var array = new[] { item1, item2 }; // C# 3.0

  • Arrays in Generic class 2009-11-24

    Is there any disadvantages in using array in generic class? If yes, what are they? If No what are the advantages? --------------Solutions------------- The main advantage I can think of for using arrays in generic classes is to avoid boxing. Specifica

  • How to initialize an array in Java? 2009-12-21

    I am initializing an array data like this : public class Array { int data[] = new int[10]; /** Creates a new instance of Array */ public Array() { data[10] = {10,20,30,40,50,60,71,80,90,91}; } } NetBeans points an error at the line data[10] = {10,20,

  • Any shortcut to initialize all array elements to zero? 2010-01-28

    In C/C++ I used to do int arr[10] = {0}; to initialize all my array elements to 0. Is there a similar shortcut in Java? I want to avoid using the loop, is it possible? int arr[] = new int[10]; for(int i=0;i<arr.length;i++) arr[i] = 0; ------------

  • Why can't I initialize an array of cstrings like this? 2010-02-16

    char sXSongBuffer[20][30]; sXSongBuffer = {"Thriller", "Don't Stop Till You Get Enough", "Billy Jean"}; Why does this return the error expected expression before ‘{’ token? The reason I want to initialize my array like this is so that I can change it

  • How to initialize an array in Tcl? 2010-07-28

    What is the proper way to initialize an empty array in Tcl? I have the following code (simplified): proc parseFile {filename results_array} { upvar $results_array results set results(key) $value } set r1 {} parseFile "filename" r1 and I get the error

  • A way to read data out of a file at compile time to put it somewhere in application image files to initialize an array 2010-09-18

    considering visual C++ compiler, Lets say I've got a file with whatever extension and it contains 100 bytes of data which are exactly the data that I want to initialize an array of char data type with a length of 100 characters with, Now apparently o

  • Array of Generic Interface 2010-10-20

    Can we create array of generic interface in java? interface Sample<T>{} in other class Sample<T> s[] = new Sample[2] ; // for this it shows warning Sample<T> s[] = new Sample<T>[2];// for this it shows error --------------Solu

Copyright (C), All Rights Reserved.

processed in 0.240 (s). 11 q(s)