Jay
Jay

Reputation: 634

Hashset "value cannot be null" error

I'm trying to execute the follow code and it works fine if myObject is != null but throws a "value cannot be null" error if myObject is null. Ideally, if myObject is null then I'd like to just have the HashSet have a single value of 0.

var ids = new HashSet<int>(myObject.Select(p => p.ID));

I've tried a couple different things. I'm not sure why I thought this would work.

var ids = new HashSet<int>(myObject.Select(p => p.ID).Where(p => p != null));

and this which seemed like it should work.

var ids = new HashSet<int>(myObject.Select(p => (p == null) ? 0 : p.ID));

Finally this worked but it seems like there's got to be a better way.

var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});

Anyone have a better way to do this?

Upvotes: 1

Views: 5123

Answers (2)

Dinerdo
Dinerdo

Reputation: 582

Now, your answer can be cleaned up just a bit:

var ids = new HashSet<int>(myObject?.Select(p => p.ID) ?? new [] {0});

Upvotes: 2

Eric J.
Eric J.

Reputation: 150108

If myObject is null, your code translates to

var ids = new HashSet<int>(null.Select(p => p.ID));

You cannot use the Select extension method off of null.

Your alternative

var ids = new HashSet<int>(myObject!= null ? myObject.Select(p => p.ID) : new int[] {0});

is the most compact form I'm aware of to meet your requirements, though certainly you could hide that complexity in a method or an extension method if you like.

Upvotes: 1

Related Questions