馃寑 Dealing with Nothing in C# - Option

It is a very common pattern to return null when something does not exist. Suppose we have a system where a UserRepository object can retrieve User objects from persistent storage - like a database. public class UserRepository { public User Get(string email) => context.Users.SingleOrDefault(u => u.Email == email); /* ... */ } This is also a very common source of bugs. Consumers of the UserRepository routinely forget to check whether the reference returned is null, causing the code to blow up at runtime unexpectedly....

December 15, 2016 路 9 min 路 1844 words 路 Botond

馃寑 Dealing with Nothing in C# - Nullable

In the previous installment of this series, we saw why the null value can be an annoying source of errors. But there are cases when you positively wish for a variable, that otherwise cannot be null, to be able to have a null value. Imagine, for example, a web site that stores the last time each user has logged in. public class User { public string NickName { get; set; } public string Email { get; set; } public string PasswordHash { get; set; } public DateTime LastLoginTime { get; set; } } If a user has just registered but they haven鈥檛 yet logged in, we want the LastLoginTime property to be somehow empty....

November 30, 2016 路 8 min 路 1594 words 路 Botond

馃寑 Dealing with Nothing in C# - The Null Object Pattern

The null reference is so ubiquitous, such an integral part of our experience as programmers, that it would be hard to imagine a world without it. Yet it is the source of so much frustration and actual financial loss that it is well worth the effort to think about some alternatives. But what exactly is the problem? Let鈥檚 imagine we have a system where customers can place orders. The orders contain line items that have a reference to a product and they store the quantity ordered....

November 11, 2016 路 4 min 路 704 words 路 Botond