Search code examples
c#listanonymous-typesenumerable

Is there a way to specify an anonymous empty enumerable type?


I'm returning a Json'ed annonymous type:

IList<MyClass> listOfStuff = GetListOfStuff();

return Json(
   new {
       stuff = listOfStuff
   }
);

In certain cases, I know that listOfStuff will be empty. So I don't want the overhead of calling GetListOfStuff() (which makes a database call).

So in this case I'm writing:

return Json(
   new {
       stuff = new List<ListOfStuff>()
   }
);

which seems a bit unnecessarily verbose. I don't care what type of List it is, because it's empty anyway.

Is there a shorthand that can be used to signify empty enumerable/list/array? Something like:

return Json(
   new {
       stuff = new []
   }
);

Or have I been programming JavaScript too long? :)


Solution

  • Essentially you want to emit an empty array. C# can infer the array type from the arguments, but for empty arrays, you still have to specify type. I guess your original way of doing it is good enough. Or you could do this:

    return Json(
       new {
           stuff = new ListOfStuff[]{}
       }
    );
    

    The type of the array does not really matter as any empty enumerable will translate into [] in JSON. I guess, for readability sake, do specify the type of the empty array. This way when others read your code, it's more obvious what that member is supposed to be.