Kieran
Kieran

Reputation: 656

Is there a version of null but for list?

I have a unit test that I am trying to write.

I have this section as part of a working version:

List<MyClass> queryResult = new List<MyClass>(){};

A.CallTo(() => _dataContext.GetAll<MyClass>()).Returns(queryResult.AsQueryable());

However, I would rather put something like "null" instead of "queryResult.AsQueryable()", Then there would be no need to create an empty list.

But GetAll will return a list empty or full by the looks of things. Therefore, null won't work.

Is there something like "List.Empty" that I can use instead?

Thanks

Upvotes: 0

Views: 232

Answers (2)

E. Shcherbo
E. Shcherbo

Reputation: 1148

You can use

Enumerable.Empty<MyClass>().ToList()

But I can not see any differences in this case.

Upvotes: 0

Marc Gravell
Marc Gravell

Reputation: 1062780

There are Array.Empty<T>() and Enumerable.Empty<T>() that might work for you. Neither of them allocates a new object per-call (they are both backed by a static T[] field on a generic class - EmptyArray<T>.Value or EmptyEnumerable<T>.Instance, although these are both implementation details)

Upvotes: 9

Related Questions