Random thoughts of wisdom - the personal blog of Michael Holm Andersen

C# null-coalescing operator

I not-so-well known “secret” in C# is the null-coalescing operator. It is used to define a default value for nullable value types or reference types. Let’s look at an example.

Let’s say your favorite ORM have created a Product class – to load a Product from your Repository, and if none is found, make a new instance, you can use the ?? operator like so:

Product p;
p = productRepository.GetProductByEAN(ean) ?? new Product();

Pretty nice and clean code if you ask me.

That’s it for now .. back to work Smiley