Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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? :)

like image 511
fearofawhackplanet Avatar asked Aug 02 '10 16:08

fearofawhackplanet


4 Answers

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.

like image 126
Igor Zevaka Avatar answered Oct 13 '22 05:10

Igor Zevaka


You could use Enumerable.Empty to be a little more explicit:

return Json(
    new {
        stuff = Enumerable.Empty<ListOfStuff>()
    }
);

Although it isn't shorter and doesn't get rid of the type argument.

like image 45
Gabe Moothart Avatar answered Oct 13 '22 07:10

Gabe Moothart


dynamic is also a better option when dealing with an anonymous type

Enumerable.Empty<dynamic>()

this worked well for me

like image 40
Uttam Ughareja Avatar answered Oct 13 '22 07:10

Uttam Ughareja


You might not care what type of list it is, but it matters to the caller. C# does not generally try to infer types based on the variable to which it is being stored (just as you can't create overloads of methods on return type), so it's necessary to specify the type. That said, you can use new ListOfStuff[0] if you want an empty array returned. This has the effect of being immutable (in length) to the caller (they'll get an exception if they try to call the length-mutating IList<T> methods.)

like image 32
Dan Bryant Avatar answered Oct 13 '22 07:10

Dan Bryant