How to populate/instantiate a C# array with a single value?
Don't know of a framework method but you could write a quick helper to do it for you.
public static void Populate<T>(this T[] arr, T value ) {
for ( int i = 0; i < arr.Length;i++ ) {
arr[i] = value;
}
}
Initialize an integer array with a single value in C# .NET
int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();
Direct array initialization with a constant value
It's not redundant.
Suppose an exception is thrown during your initialization loop. If the CLR hasn't cleared the memory first, you might be able to "see" the original uninitialized memory, which is a very bad idea, particularly from a security standpoint. That's why the CLR guarantees that any newly allocated memory is wiped to a 0 bit pattern.
The same argument holds for fields in an object, by the way.
I suppose in both cases the CLR could check that you're not going to make the array visible elsewhere before finishing initialization, but it's a complicated check to avoid a pretty simple "wipe this area of memory".
How do I quicky fill an array with a specific value?
The other way is:
int[] arr = Enumerable.Repeat(-1, 10).ToArray();
Console.WriteLine(string.Join(",",arr));
Using Enumerable to initialize an array of arrays with the same value in C#
IMHO, Repeat()
is a better choice. Again, you were close:
Enumerable.Repeat(new[] { -1, -1 }, 8).ToArray();
You only can omit the new[]
with initializers (e.g. when declaring a variable).
Create an array full of -1;
You could do this:
public static int[] Initialize( this int[] instance , int value )
{
if ( instance == null ) throw new ArgumentNullException("instance") ;
for ( int i = 0 ; i < instance.Length ; ++i )
{
instance[i] = value ;
}
return instance ;
}
which would let you say something like
int[] foo = new int[2048].Initialize(-1) ;
You might get some performance increase by going unsafe and using pointers, since you won't incur the overhead of array bounds checking, something like this:
public static unsafe int[] Initialize( this int[] instance , int value )
{
if ( instance == null ) throw new ArgumentNullException("instance") ;
fixed ( int *addr = instance )
{
int *p = addr ;
int *pMax = addr+instance.Length ;
while ( p < pMax )
{
*(p++) = value ;
}
return instance ;
}
If you'll only ever want to set the array to -1, you can make it even faster by using memset()
, since we know that all the bytes will be 0xFF. So...
public static unsafe int[] InitializeToMinus1( this int[] instance )
{
if ( instance == null ) throw new ArgumentNullException("instance");
fixed( void *p = instance )
{
IntPtr addr = new IntPtr(p) ;
const int hexFF = 0x000000FF ;
int bytes = instance.Length * sizeof(int) ;
memset( addr , hexFF , bytes ) ;
}
return instance ;
}
[DllImport("msvcrt.dll", EntryPoint="memset", CallingConvention=CallingConvention.Cdecl, SetLastError = false)]
public static extern IntPtr memset( IntPtr addr , int c , int count ) ;
fill an array in C#
Write yourself an extension method
public static class ArrayExtensions {
public static void Fill<T>(this T[] originalArray, T with) {
for(int i = 0; i < originalArray.Length; i++){
originalArray[i] = with;
}
}
}
and use it like
int foo[] = new int[]{0,0,0,0,0};
foo.Fill(13);
will fill all the elements with 13
Adding values to a C# array
You can do this way -
int[] terms = new int[400];
for (int runs = 0; runs < 400; runs++)
{
terms[runs] = value;
}
Alternatively, you can use Lists - the advantage with lists being, you don't need to know the array size when instantiating the list.
List<int> termsList = new List<int>();
for (int runs = 0; runs < 400; runs++)
{
termsList.Add(value);
}
// You can convert it back to an array if you would like to
int[] terms = termsList.ToArray();
Edit: a) for loops on List<T> are a bit more than 2 times cheaper than foreach loops on List<T>, b) Looping on array is around 2 times cheaper than looping on List<T>, c) looping on array using for is 5 times cheaper than looping on List<T> using foreach (which most of us do).
Related Topics
"On Exit" for a Console Application
Updating Gui (Wpf) Using a Different Thread
Handling Unhandled Exceptions Problem
"Self Referencing Loop Detected" Exception with JSON.Net
Token Based Authentication in ASP.NET Core
Benchmarking Small Code Samples in C#, Can This Implementation Be Improved
Global Hotkey in Console Application
Using' Statement VS 'Try Finally'
Exclude Property from Serialization via Custom Attribute (JSON.Net)
How to Return a Value from a Form in C#
What Does $ Mean Before a String
Returning Anonymous Type in C#
Using Multiple Versions of the Same Dll
What Strategies and Tools Are Useful for Finding Memory Leaks in .Net