From the code supplied there is no value assigned to arrayA[3]
the array is simply a container for values and sets each value to the default value for the type similar to going default(string)
.
Now as string
is a reference type the default value for the string is null
however a value type int
for example will have a default value of 0
.
We can easily test this such as.
string[] arrayA = new string[31];
var s = arrayA[3]; //is null as string is a reference type
int[] arrayB = new int[31];
var i = arrayB[3]; //equals 0 as default(int) = 0
Now as pointed in comments there are easy ways to populate an array and the referenced comment points to How to populate/instantiate a C# array with a single value?
The snippet below is from the answer above
public static void Populate<T>(this T[] arr, T value ) {
for ( int i = 0; i < arr.Length;i++ ) {
arr[i] = value;
}
}
This can be called by:
arrayA.Populate("");
So in the call:
commA.Parameters.Add("@ColumnA", SqlDbType.NVarChar).Value = arrayA[3];
In fact arrayA[3] = null
EDIT
The snippet above is an extension method (as seen by the this
keyword on the first parameter in the method signature). This must be in a static class
similar to below.
public static class ArrayExtensions
{
public static void Populate<T>(this T[] arr, T value)
{
for (int i = 0; i < arr.Length; i++)
{
arr[i] = value;
}
}
}
As for the question
Is there a way to populate the all string[] arrayAwith "" without
using for loop?
All the methods to set the default value of all items in an array will require a loop of some sort and the loop may be a foreach
or for
under the hood somewhere.
You could also create a method that would create an array for you of a specified size with a default value.
public static T[] CreateArray<T>(int capacity, T defaultValue)
{
var array = new T[capacity];
array.Populate(defaultValue);
return array;
}
Which could then be called as:
var arrayC = ArrayExtensions.CreateArray<string>(31, "");
s = arrayC[3]; //equals ""
However that starts to look too lazy to me.