check against: null vs default()?

Viewed 12987

I want to check if a reference type is null. I see two options (_settings is of reference type FooType):

if (_settings == default(FooType)) { ... }

and

if (_settings == null) { ... }

How do these two perform differently?

7 Answers

Now that we don't need to pass the type to default anymore, default is preferred.

  • It is just as readable

  • It can be used both for value and reference types

  • It can be used in generics

    if (_settings == default) { ... }

Also, after calling

obj = enumerable.FirstOrDefault();

it makes more sense to test for default after that and not for null. Otherwise it should have been FirstOrNull, but value dont have a null value but do have a default.

Related