So I've got a collection of struct
s (it's actually a WCF datacontract but I'm presuming this has no bearing here).
List<OptionalExtra> OptionalExtras;
OptionalExtra
is a struct
.
public partial struct OptionalExtra
Now I'm running the below statement:
OptionalExtra multiOptExtra = OptionalExtras.Where(w => w.Code == optExtra.Code).FirstOrDefault();
if (multiOptExtra != null)
{
}
Now this won't compile:
the operator != cannot be applied to opperands of type OptionalExtra and
'<null>'
After a little googling I realised it's because OptionalExtra
is a struct
. Which I believe is not nullable unless defined as a nullable type?
So my question is, if my where
statement returns no results what will be the outcome of the FirstOrDefault
call? Will it thrown an exception?
Incidently this should never happen but better safe than sorry.
If
default(OptionExtra)
is still a valid value, it's better to change your code to thisAssuming Code is a string for the purposes of my answer, you should be able just to test that value for its default.
its provide you defualt value for your structure like as below
other option to handle is make use of default value like as below
As others have said, the result of your code when no elements match will be:
If you want a null returned, you can cast your list to
OptionalExtra?
You can then test for
null
If you want to check for null, use System.Nullable collection:
Note that you have to use Value to access the element.
The result will be the default value of your struct, e.g.
default(OptionalExtras)
.Whereas for a reference type the default value is
null
.