Method exits without exception when trying to access first element of an empty collection (Edit: Known Form Load issue)

StackOverflow https://stackoverflow.com/questions/18027296

  •  21-06-2022
  •  | 
  •  

Domanda

I noticed a method I wrote exits early and doesn't throw any exception when trying to access the first element in a collection (like string[] or List) if it is empty. E.g.

var emptyList = new List<string>();
var aha = emptyList.Where(i => i == "four"); 
var props = aha.First();
//anything after here in the same method does not run

Is this correct, how can that be a useful feature in the compiler?! (using .Net 4)

Edit full winforms program:

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        var emptyList = new List<string>();
        var aha = emptyList.Where(i => i == "four");
        var props = aha.First(); //throws exception 



        var fdsfsa = 0;
    }


    private void useref() {

        var emptyList = new List<string>();
        var aha = emptyList.Where(i => i == "four");
        var props = aha.First(); //exits method, doesn't throw exception?

        var asdf = 0;
    }

    private void Form1_Load(object sender, EventArgs e)
    {
        useref();
    }
}
È stato utile?

Soluzione

No, that will fail with an InvalidOperationException. I'm sure you're just catching the exception in the calling code. It's very easy to show - just take your exact code and put it into a short but complete sample:

using System.Collections.Generic;
using System.Linq;

class Test
{
    static void Main()
    {
        var emptyList = new List<string>();
        var aha = emptyList.Where(i => i == "four"); 
        var props = aha.First();
    }
}

Result:

Unhandled Exception: System.InvalidOperationException: Sequence contains no elements
   at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
   at Test.Main()

So your next step is to work out why you're not seeing the exception - and we can't help with that.

Altri suggerimenti

Try the following:

try {
    var emptyList = new List<string>();
    var aha = emptyList.Where(i => i == "four"); 
    var props = aha.First();
} catch(InvalidOperationException ex) {
    //ex.message
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top