"Tony Hoare, the inventor of the null reference, called it his ‘billion dollar mistake.’ Null is a disaster because it means that every reference type has a magic value that will destroy your program. For value types, we now have ‘normal’ value types and nullable value types to express the difference between, say, ‘this function returns an integer’ and ‘this function might return an integer, or it might not.’ But we don’t have that for reference types."For example, in C# we have int for a normal value and int? for a nullable value. But for reference type like a string, you just don't know until you check it or your program crashed on it.
Ivan Towlson has mentioned a good and compact way to handle nullable type with a Maybe class. Since I don't have his source code, I created my own. If you are interested to use it, just simply download the Maybe.cs class under the MaybeApplication folder from github and use it in your own program. Or you can download the whole project. The project is created in VS2010.
Why should you care? What does the class do?
Ok, instead of doing the null check the old fashion way
static string DemoTheOldWayOfNullChecking() { Contact contact = new Contact(); contact.Name = "Sean"; contact.Phone = "12345678"; contact.Age = 24; //contact.PersonalPet = new Pet() //{ // PetName = new PetName() // { // Name = "My Pet" // } //}; if (contact == null) return null; if (contact.PersonalPet == null) return null; if (contact.PersonalPet.PetName == null) return null; var petName = contact.PersonalPet.PetName.Name; if (petName == null) return null; return petName; }
Now with some Linq awesomeness, you can do something like this
static string DemoTheNewWayOfNullChecking() { Contact contact = new Contact(); contact.Name = "Sean"; contact.Phone = "12345678"; contact.Age = 24; //contact.PersonalPet = new Pet() //{ // PetName = new PetName() // { // Name = "My Pet" // } //}; // Maybe class allow you to do something similar to int? for the reference types. MaybemaybeContact = new Maybe (contact); var maybePetName = from c in maybeContact from cp in c.PersonalPet from pn in cp.PetName select pn.Name; if (maybePetName.HasValue) return maybePetName.Value; return null; }
Reference:
http://www.mindscapehq.com/blog/index.php/2012/03/27/5-12-f-features-every-c-programmer-should-lust-after/
No comments:
Post a Comment