The Great Debate - Single or First


Ah, the joy of having options! I have definitely had some spirited debates regarding which method to use

.First() or .Single()

I am firmly on the side of First. I know, I know ... the Single folks are adamant I’m a loon. That’s ok 😀


My personal experience has pushed me to deciding that First is a better option because if you use Single and you get any other return than 1 object - you get an error. I rarely want an error even when I have it inside a try catch.

When I have had to troubleshoot code that I was maintaining and didn’t write - I have come across an entire code block being missed because someone used the Single, rather than First. When the sproc sent back 2 identical values - it resulted in an error. Had this been coded using First, this would not have caused an error.


var clientId = Request.Params.GetValues("clientid").First(); 
 var clientid = Request.Params.GetValues("clientid"). Single(); //Error


Yes, we all want to code as if what we expect is always what we get. But realistically, this doesn’t happen. Let’s say your DBA writes a sproc to get a Person record based on the name, email, and employee id. The employee id is supposed to be unique. Your SQL table’s unique id is the UserID, which is guaranteed unique based on the SQL requirement. The employee id is unique based on human entry by an accountant. If the sproc does not use the UserID in the select statement, if the employee id is accidentally duplicated, your Single requirement fails. Another potential is if the sproc finds nothing and returns a null, this also fails and causes an error. The Single usage is very specific and must return 1 value and nothing else.

As shown below, including the unique identifier or not, you still get 2 resulting rows, unless you use the 'DISTINCT' keyword. The select result is key when using Single in your code.



Because of this kind of thing, I err on the side of caution and code against human error, as well as test edge cases. It tends to add some verifications and validations, however I write solid code that passes anything a QA throws at it, as well as production quality without unintentional errors.

I also prefer using FirstOrDefault() over SingleOrDefault() for the same reason, however this is a little less stringent because it allows for getting no result. Yes, I know. Now you have to do a null check on the result. However, I would rather add 1 null check line of code than have an error that could potentially lose important data.




This argument will not always hold up to every potential usage. There are valid reason to use Single or SingleOrDefault() as well. I just find it less versatile in my experience.

Its food for thought as you solidify your coding style. Tell me what you think about using Single vs First in the comments!



13 views

Tags: