简体   繁体   中英

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.

EDIT:

This works fine

class Program
{
    static void function(List<int> array)
    {
        array.Add(42);
    }

    static void Main(string[] args)
    {
        List<int> array = new List<int>();
        function(array);
    }
}

And this one too

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

    static void Main(string[] args)
    {
        int[] array;
        function(out array);
    }
}

But the following throws an exception

class Program
{
    static void function(out List<int> array)
    {
        array = new List<int>(25);
        array[0] = 42;
    }

    static void Main(string[] args)
    {
        List<int> array;
        function(out array);
    }
}
Class Demo
{


 static void main (string[] args)
 {
    var result=Add();
    Console.WriteLine(result[0]);
 }

  static List<int> Add ()
  {
    var listOfints= new List<int>();
    listOfints.Add(42); //either this or declare an array of integers and get it initialized by reading the user value and pass the same as param here to initialize and return the array
    return listOfints;
  }

}

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;
    }
}

I think the reason that you're having problems assigning value [0] to ac# list is that unless you create a List<> collection with a predefined start size it will be empty. Thus entry [0] is null and can't be set.

If you want to directly access element 0, use this:

  void function(out List<int> list)
  {
     list = new List<int>(25);
     list[0] = 42;
  }

If instead you don't need to / know the initial allocation size of the List, use this: (recommended IMHO)

  void function(out List<int> list)
  {
     list = new List<int>();
     list.Add(42);
  }

Good luck!

Another way (Although it's recommended to use a List<int> )

Replace int * with out int[]

public class Program
{
    public static void Main()
    {
        int[] array;
        function(out array);
        Console.WriteLine(array[0]);
    }

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

Output

42

As mentioned above c# uses references. Pointers are supported but you would need to write unmanaged code..
More info about references here https://msdn.microsoft.com/en-us/library/14akc2c7.aspx

A sample is below.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace alistnamespace
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> my_list=new List<int>();
            functionaddtolist(ref my_list);
            for(int i=0;i<my_list.Count;i++)
            {
                Console.WriteLine("List item " + i.ToString() + "=" + my_list[i]);
            }
        }

        static void functionaddtolist(ref List<int> mylist_ref)
        {
            mylist_ref.Add(42);             //Add one element

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM