Search code examples
c#out

C# out variable in list


i m studying the book Exam Ref 70-483:Programming in C#.

in the chapter Using concurrent collection, there is an example:

   #region Listing 1-30
        ConcurrentBag<int> bag = new ConcurrentBag<int>();
        bag.Add(42);
        bag.Add(21);
        int result;
        if (bag.TryTake(out result))
            Console.WriteLine(result);
        if (bag.TryPeek(out result))
            Console.WriteLine("There is a next item: {0}", result);
        #endregion

the question is : how it connect the variable int result with bag ?

there is no decalaration result = bag.DoSomeThingInLinq.

thanks in advance


Solution

  • how it connect the variable int result with bag ?

    bag.TryTake(out result)
    

    The line above attempts to remove and return an item from the bag. If successful (i.e. when it returns true) then the out parameter result will contain the value taken.

    When a method uses an out parameter, this means that it will be passed by reference. The method using it then has to assign a value to it.

    See:

    ConcurrentBag

    out parameter modifier