Paulo Morgado

.NET Development & Architecture

Recent Articles

view all

Events

Projects

Recent Readers

Visitor Locations

Visitor Locations

Disclaimer

The opinions and viewpoints expressed in this site are mine and do not necessarily reflect those of Microsoft, my employer or any community that I belong to. Any code or opinions are offered as is. Products or services mentioned are purchased by me, made available to me by my employer or the manufacturer/vendor which doesn't influence my opinion in any way.

LINQ: Single vs. SingleOrDefault

Like other LINQ API methods that extract a scalar value from a sequence, Single has a companion SingleOrDefault.

The documentation of SingleOrDefault states that it returns a single, specific element of a sequence of values, or a default value if no such element is found, although, in my opinion, it should state that it returns THE single, specific element of a sequence of ONE value, or a default value if no such element is found. Nevertheless, what this method does is return the default value of the source type if the sequence is empty or, like Single, throws an exception if the sequence has more than one element.

I received several comments to my last post saying that SingleOrDefault could be used to avoid an exception.

Well, it only “solves” half of the “problem”. If the sequence has more than one element, an exception will be thrown anyway.

In the end, it all comes down to semantics and intent. If it is expected that the sequence may have none or one element, than SingleOrDefault should be used. If it’s not expect that the sequence is empty and the sequence is empty, than it’s an exceptional situation and an exception should be thrown right there. And, in that case, why not use Single instead? In my opinion, when a failure occurs, it’s best to fail fast and early than slow and late.

Other methods in the LINQ API that use the same companion pattern are: ElementAt/ElementAtOrDefault, First/FirstOrDefault and Last/LastOrDefault.

Comments

Arun Mahendrakar said:

Nice corollary to your previous post.

Arun

# March 30, 2010 12:14 AM

Paulo Morgado said:

Thanks, Arun.

# March 30, 2010 4:01 AM

jyotsana said:

Nice..thanks for help.

# June 17, 2011 12:51 AM

Javad said:

Even though I've read book about Linq but I feel your articles are more comfortable for me.

Thank you And God bless you.

# June 23, 2011 11:23 PM

Paulo Morgado said:

Thanks jyotsana and Javad. Always glad to help.

I like to bring things down to earth for the common developer.

You might also want to take a look Jon Skeet's Edulinq blog posts (msmvps.com/.../default.aspx) and James Michael Hare C#/.NET Little Wonders blog posts (geekswithblogs.net/.../11989.aspx).

# June 24, 2011 4:14 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)