6

I've couple of action methods with parameters of IList type.

public ActionResult GetGridData(IList<string> coll)
{
}

The default behavior is when no data are passed to action method the parameter is null.

Is there any way to get an empty collection rather then null application wide ?

user49126
  • 1,825
  • 7
  • 30
  • 53

2 Answers2

6

Well, you could either do this:

coll = coll ?? new List<string>();

Or you would need to implement a ModelBinder that will create an empty list instead of returning null. E.g.:

public EmptyListModelBinder<T> : DefaultModelBinder
{
  public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) 
  {
    var model = base.BindModel(controllerContext, bindingContext) ?? new List<T>();
  }
}

And wired up as:

ModelBinders.Binders.Add(typeof(IList<string>), new EmptyListModelBinder<string>());

I'd probably stick with the argument check though...

Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
  • 1
    Why would you stick with null checking ? It's a best practice to return empty collection instead of null. – user49126 Jan 03 '12 at 10:12
  • Why do you think that? What if there is a difference between what `null` represents as to what an empty list represents? What happens in your unit tests for your controller if you pass in null? They will fail. You've got a public method, this forms part of your API, which means you should be argument checking those inputs. I don't remember any guidelines stating that an empty list is better than null... – Matthew Abbott Jan 03 '12 at 10:15
  • Have a look here http://stackoverflow.com/questions/1969993/is-it-better-to-return-null-or-empty-collection – user49126 Jan 03 '12 at 10:19
  • 4
    You're not **returning** anything..., you're checking an **input** argument. – Matthew Abbott Jan 03 '12 at 10:21
  • 1
    Hmm you right, but in my case is this agrument used in many action methods in the same manner, so It looks to me like violation of the DRY principle. – user49126 Jan 03 '12 at 10:32
1

simply do it yourself

public ActionResult GetGridData(IList<string> coll)
{
    if(coll == null)
        coll = new List<String>();
    //Do other stuff
}
Maheep
  • 5,539
  • 3
  • 28
  • 47