-7

here my code is its showing the parameter you have passed is null:-

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if (Seats.Count(x => x.IsSelected) == 0)
     {
            return "you didnt select any seats";
     }
     else
     {
           StringBuilder sb = new StringBuilder();
           sb.Append("you selected");
           foreach (Seat seat in Seats)
           {
               if (seat.IsSelected)
               {
                   sb.Append(seat.Name + " ,");
               }
            }
           sb.Remove(sb.ToString().LastIndexOf(","), 1);
           return sb.ToString();
     }   
}
Chandan Kumar
  • 4,570
  • 4
  • 42
  • 62
Debashish Dwivedi
  • 327
  • 2
  • 5
  • 13

2 Answers2

4

The exception appears because - as Lucero already mentions - Seats is null. In contrast to a usual method you don´t get a NullReferenceException here because Count is an extension-method:

public static int Count(this IEnumerable<T> source)
{
    if (source == null) throw new ArgumentNullException("source");
}

So as you see the method throws an ArgumentNullException instead of a NullReferenceException if source is null.

As an aside don´t use Count to check if your collection has items, use Any instead, as it doesn´t enumerate the complete collection and returns when the very first matching the condition was found.

EDIT: If You´d about to use another method which is a normal instance-method you´d get an NRE however:

Seats.DoSomething(); // throws NRE when Seats = null

So check if the argument is null before using it:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
    if (Seats == null || !Seats.Any(x=> x.IsSelected))
        return "you didnt select any seats";
}
MakePeaceGreatAgain
  • 35,491
  • 6
  • 60
  • 111
2

Seats will be null if you call the method without matching data / query argument. You need to also check that, like so for instance:

[HttpPost]
public String Indexhome( IEnumerable<Seat>  Seats )
{
     if ((Seats == null) || !Seats.Any(s => s.IsSelected))
     {
            return "you didnt select any seats";
     }
     else
     {
           return "you selected " + string.Join(", ", Seats.Where(s => s.IsSelected).Select(s => s.Name));
     }   
}
Lucero
  • 59,176
  • 9
  • 122
  • 152