Junipella Junipella - 10 days ago 7
C# Question

How to dynamically create a List in a function in C#

I have a code written in c. I have a pointer to int in main and I pass it to a function. This function allocates memory and populates the array, then it returns. Basically looks like this:

main()
{
int* array;
function(&array);
}

void function(int** array)
{
int size = 25;
*array = malloc(size);
(*array)[0] = 42;
}


Size is not known in main. How do I do this in C#? I tried with List but I cannot make it work. I have tried both List and ref List, and they both give Index was out of range.

Answer

has the ref keyword for this purpose. Although it is not required in this case because an array is a reference type anyway it is a good idea nevertheless because it conveys the design intent. Better yet to use the out keyword as the argument to the function doesn't need to be initialized before the call.

Try this:

class Program
{
    static void Main(string[] args)
    {
        int[] a;
        function(out a);
        Debug.WriteLine(a.Length);
    }

    public static void function(out int[] array)
    {
        array=new int[25];
        array[0]=42;
    }
}

Edit 1 - Alternate way with returning an array

class Program
{
    static void Main(string[] args)
    {
        int[] a = CreateArray();
        Debug.WriteLine(a.Length);
    }

    public static int[] CreateArray() 
    {
        int[] array=new int[25];
        array[0]=42;
        return array;
    }
}

Edit 2 - Example with two out parameters

class Program
{
    static void Main(string[] args)
    {
        int[] akw, zuk;
        function(out akw, out zuk);
        Debug.WriteLine(akw.Length);
        Debug.WriteLine(zuk.Length);
    }

    public static void function(out int[] A, out int[] B) 
    {
        A=new int[25];
        B=new int[15];
        A[0]=42;
        B[0]=21;
    }
}