views:

46

answers:

5

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

A: 

I guess you are talking about C# here. My knowledge is limited in C# but I don't think you can create a new object with no type. Why can't you return a generic new List[] ? (might be mixing Java generics here, am not sure is one can return a generic type list in C#).

Gangadhar
A: 

send a generic type?:

List<Object>()

or send an empty object array: new Object[]

Nealv
+2  A: 

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.)

Dan Bryant
See Igor's answer as it's more correct; as this is going through JSON, any empty array is sufficient.
Dan Bryant
+1  A: 

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.

Gabe Moothart
+2  A: 

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.

Igor Zevaka
+1 for pointing out that JSON doesn't care about the type in this case; I wasn't aware of that
Dan Bryant