Search code examples
c#listinitializationout

C# method out parameter list initialization doesn't works with Clear()


I found, that construction

Method(out List<T>list)
{
    list.Clear();      // doesn't allowed to initialyze List<T>list
    list = null;       // is accepted by VSTO, however, is not so good
}

Any suggestion please?


Solution

  • You cannot use unassigned parameter withing this method. There is simple rule: use out whether parameter is not initialized or use ref if you pass initialized parameter to method.

    This code will run correctly:

    void Method<T>(ref List<T> list)
    {
        list.Clear();
        list = null;
    }
    

    Read more about differencies in this question: What's the difference between the 'ref' and 'out' keywords?