How to create a default instance of a type T
A problem I’ve come across in the past when writing ORM solutions is when I need to create a new instance of generic type T but set to a NULL or 0 value. Value types I need to set to null but reference types I need to set to 0. How do I do the right thing? Here’s a bad way:
if (typeof(container) == typeof(int)) container = 0; else if (typeof(container) == typeof(Customer)) container = null;
Using this method means lots of if … else if …else by checking type. How ugly! There has to be a better way, I thought. So I gave up and got on with something else.
Months later, it turns out there IS a better way: the default keyword:
t container = default(containerType);
This keyword gives you a NULL or 0 value based on the type you pass it. I don’t know whether it’s faster or more efficient, but hey, it’s a lot less code for you to write, and you can be pretty sure they’ve covered all the edge cases.