Out parameter might not be initialized before accessing

Tarec picture Tarec · Feb 5, 2014 · Viewed 14.1k times · Source

Why is the code below

private static List<WorkflowVariableDataSet> MergeDatasetsListBranch(out List<WorkflowVariableDataSet> datasetsList)
{
    if(datasetsList == null)
        datasetsList=new List<WorkflowVariableDataSet>();
    datasetsList=new List<WorkflowVariableDataSet>();
    return datasetsList;
}

generating an error at the first if statement:

Out parameter 'datasetsList' might not be initialized before accessing.

I know it should be uninitialized at this point, but the word might suggest that the error lies in possible uninitialized object accessing (when it's not even accessed, it's the reference, that is checked). Ofc that doesn't happen with ref keyword, but I'm curious how is the reference checking violating out-parameters policy.

EDIT I've edited the question and the example: the out object will be initialized inside the method anyway. The question is: WHY uninitialized object cannot be null compared? How is that different from:

object o;
if(o==null)
    ...

Answer

Tim Schmelter picture Tim Schmelter · Feb 5, 2014

Compiler Error CS0269

Use of unassigned out parameter 'parameter' The compiler could not verify that the out parameter was assigned a value before it was used; its value may be undefined when assigned. Be sure to assign a value to out parameters in the called method before accessing the value. If you need to use the value of the variable passed in, use a ref parameter instead.

So treat an out-parameter as unassigned. You are the one who is responsible.

So just remove the if:

datasetsList = new List<WorkflowVariableDataSet>();

If you want to process a list that is passed to this method use ref intead (as suggested above):