SCA1031: Return of a Container the Method Does Not Own
Do not return a container that the method does not own.
Example
Task<LockGuard> GetCachedAsync() => _cached; // SCA1031: every caller would get the same task
List<LockGuard> Build()
{
var list = new List<LockGuard>();
list.Add(myLock.Enter());
return list; // OK: the method's own
}
How to Fix
- Return a container that the method created and handed to nothing that keeps it.
- Mark the method
[return: Borrowed], if it keeps what it returns. Its callers then treat the result as stored. See Containers in Your API. - For a delegate, use a delegate type whose return value is marked
[return: Borrowed].
Details
Returns
A method, a local function, a lambda or an operator returns, or yields, a container that something else still holds, including an array or an ArraySegment<T>. Callers treat the result of a call as a new value, so every caller would read its non-copyable values as new.
A local counts as held by something else after any use other than those that leave it the method's own, and the message names that use. See Locals That the Method Owns.
Delegates
A delegate's result counts as a new value, so a delegate must not be made from something that hands out a stored container:
// tasks is a Bag<Task<LockGuard>>, declared as Bag<[NonCopyable] T>
Func<Task<LockGuard>> next = tasks.Take; // SCA1031: 'Take' hands out what the bag still holds
The same goes in generic code for a function that returns a value of a marked type parameter. See Delegates and Conversions With Nothing Written.
Conversions With Nothing Written
An object of a class that derives from a framework container, such as class Guards : List<LockGuard>, is stored where it becomes the container. So is an object of a type whose own code decides what it holds. Three places do that with no cast in the code, and each gets a warning:
| Where | Example |
|---|---|
| An override that returns the derived class where the base returns the container | override Guards Get() over List<LockGuard> Get() |
| A method group returning the derived class, for a delegate that returns the container | Func<List<LockGuard>> f = MakeGuards; |
| A variant conversion | Func<Guards> to Func<List<LockGuard>> |
See Also
These articles explain the rule behind this warning:
- Returning a Container - which containers a method may return, and the Borrowed mark.
- What a Member on the Symbol List Hands Out - reads from stored containers.
Didn't add this analyzer yourself? See Why Am I Seeing This?