Why does the list in uipath need to be initialized and the array does not

Why does the list in UiPath need to be initialized and the array does not

Hi @1545030349

In UiPath, a list variable needs to be initialized before it can be used. This is because a list is a dynamic data structure, which means that its size can change during runtime. When you initialize a list, you are essentially creating an instance of the list with a specific capacity. This capacity can be increased or decreased as items are added or removed from the list.

On the other hand, an array is a fixed-size data structure, which means that its size is determined when it is created and cannot be changed during runtime. When you declare an array variable, you must specify its size, and memory is allocated for the array accordingly. Since the size of an array is fixed, it does not need to be initialized before it can be used.

Best Regards.

3 Likes

Can you provide an example of how to make a List and initialize it?

Here’s an example of how you can define a List of Strings:

  1. In the Variable Panel, click on “Create Variable”.
  2. Enter a name for your variable, for example “myList”.
  3. For the variable Type, type in “List” in the search box and select <System.Collections.Generic.List<T>> from the dropdown.
  4. Now, you need to specify the type of items the list will hold. Click on “Browse for Types…”. In the popup window, search for “string” and select System.String. Click on OK.
  5. Now, the Variable type should look like System.Collections.Generic.List<System.String>. Leave the Scope as it is.

image

To initialize the list in an Assign activity, you would write:

myList = new List(Of String)

You can also initialize the list with some data:

myList = New List(Of String) From {"Value1", "Value2", "Value3"}

Now, you can use the list in your UiPath activities.

Examples:

In UiPath, both Lists and Arrays need to be initialized before they can be used, but they use different methods for initialization.

The confusion might come from the fact that in UiPath Studio, you can define an array using default literal notation like: {"element1", "element2", "element3"}, directly within an Assign activity. This is a shorthand way of defining and initializing an array all at once, and it might appear as if you’re not really initializing it, but you are.

For Lists, there’s no equivalent literal notation. Instead, Lists are initialized using the New keyword: new List(Of String). You can add elements to the list using the .Add() or .AddRange() methods.

Another important difference is that Arrays have a fixed size once they’re initialized, while Lists are dynamic and have methods to Add and Remove items. So if you need a fixed-size collection, an Array is appropriate. If you need a dynamic-size collection, a List is usually better.

So, to sum up, both Arrays and Lists need to be initialized before using, but they do so in different ways and offer different functionalities.