Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the default value of an optional 'List(Of t)' parameter to an empty list?

In this example, I can't figure out how to set the optional parameter c to an empty List(Of thing):

Sub abcd(a as something, b as something, optional c as List(Of thing) = ?? )
    ' *stuff*
End Sub

I considered setting c to null, but that seems like a bad thing to do.

like image 528
temporaryname Avatar asked Dec 03 '14 04:12

temporaryname


People also ask

How do you fix the default value of an optional parameter must be constant?

Use the '=' operator only when you need to pass a default value to your variables hence, making them optional parameters. This is called a canonicalized constructor.

Why shouldn't you make the default arguments an empty list?

Why shouldn't you make the default arguments an empty list? Answer: d) is a bad idea because the default [] will accumulate data and the default [] will change with subsequent calls.

How do you make a parameter optional in darts?

A parameter wrapped by { } is a named optional parameter. Also, it is necessary for you to use the name of the parameter if you want to pass your argument.

How do you pass an empty list to a function in Python?

Using square brackets [] Lists in Python can be created by just placing the sequence inside the square brackets [] . To declare an empty list just assign a variable with square brackets.


2 Answers

You can't. Optional values have to be compile-time constants. The only compile-time constant you can assign to List(Of T) is Nothing.

What you can do is overload that method with one that omits the List(Of T)parameter. This overload can then pass an empty List(Of T) to the original method:

Sub abcd(a as something, b as something)
    abcd(a, b, New List(Of T)())
End Sub

Sub abcd(a as something, b as something, c as list(of thing))
    doStuff()
End Sub
like image 89
MarcinJuraszek Avatar answered Nov 15 '22 06:11

MarcinJuraszek


I appreciate this is an old question (and shame on me for breaching etiquette in replying) but...

I had exactly the same issue today. It was resolved by passing an object...

Sub abcd(a as something, b as something, optional c as Object = Nothing )
    Dim lstC as new List(Of thing)
    If Not IsNothing(c) then
        lstC = c
    End IF
    ' Then in your code you just have to see if lstC.Count > 0
    ' *stuff*
End Sub
like image 41
Tym Avatar answered Nov 15 '22 06:11

Tym