简体   繁体   中英

Testing for 'null' vs. testing for 'default(T)'

When I started using LINQ one of the samples I copied used this pattern, which I have been using ever since. Here's an example from a recent bit of code:

var heartbeat = db.HeartBeats.Where(hb => hb.macHash == macAddressHash).FirstOrDefault();
if (heartbeat != default(HeartBeat))
{
    result = heartbeat;
}

A few colleagues have expressed surprise at comparing the result of the LINQ query to default(T) rather than null .

Is there an advantage?

Advantage: no. Difference: yes.

If you use for example int , the FirstOrDefault will return 0 as default. Comparing to null is useless, comparing to default(T) isn't.

In the case of null , the expression will result to false , in the case of default(T) it results to true .

In this case, if HeartBeat is a reference type, it doesn't make any difference.

The FirstOrDefault returns null , if the type you are looking for is a reference type and your query hasn't any results. So there isn't any reason of using the default .

However, I don't think that there is any advantage of using one another. The only good thing I can think is that using null is more expressive than default(HeartBeat) . I say so, because when we use the default , at first we read the expression default(HeartBeat) and then we recall that the default type of a reference type is null . While, using null , you avoid that milliseconds of thought.

update

From MSDN documentation about FirstOrDefault , we have that the signature of this method is the following:

public static TSource FirstOrDefault<TSource>(this IEnumerable<TSource> source)

and as it is stated there:

Returns the first element of a sequence, or a default value if the sequence contains no elements .

Or in other words returns

default(TSource) if source is empty.

Otherwise the first element in source.

Take into account the above, it is more close to the documentation to make use of default(T) , where T is your type in your if statements.

However, I prefer using the default value, null , 0 , false etc. rather than default(T) . This doesn't mean in no way that's the correct approach. It's a personal opinion. You pick.

No difference here, obviously. I suppose it would make an impact when you change it to a collection of value types in the future but

1) This isn't all that common in my experience.

2) It would mean that your collection can't contain 0 although it might very well be a legitimate value.

Personally I find != null more comfortable to read.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM