In this code:
public bool SomeMethod(out List<Task> tasks)
{
var task = Task.Factory.StartNew(() => Process.Start(info));
tasks.Add(task);
}
I get an error, “Use of unassigned out parameter ‘tasks'”. Why?
In an MSDN example there’s just use of out parameter
class OutExample
{
static void Method(out int i)
{
i = 44;
}
static void Main()
{
int value;
Method(out value);
// value is now 44
}
}
Is it because of List<T>?
You have to initialize the
outparameter in the method body (that is create a newList<Task>instance and assign it to theoutparameter):I’m using the collection initializer syntax to add the task to the list, but you could call the
Addmethod instead if you prefer.You should call the method like this:
C# 7.0 has introduced new simpler syntax where you declare the variable in the call to the function with the
outparameter:As a
List<T>is passed by reference you can get rid of theoutparameter. You then have to create the list before calling the method:And call it like this:
In general it is good practice to avoid
outparameters because they can be confusing.