What’s ‘default’ for?
- by Strenium
Sometimes there's a need to communicate explicitly that value variable is yet
to be "initialized" or in other words - we’ve never changed it from its' default value.
Perhaps "initialized" is not the right word since a value type will always
have some sort of value (even a nullable one) but it's just that - how do we
tell?
Of course an 'int' would be 0, an 'enum' would the first defined value of a
given enum and so on – we sure can make this
kind of check "by hand" but eventually it would get a bit messy.
There's a more elegant way with a use of little-known functionality of: 'default'Let’s just say we have a simple Enum:
Simple Enum
namespace xxx.Common.Domain{ public enum SimpleEnum { White = 1, Black = 2, Red = 3 }}
In case below we set the value of the enum to ‘White’ which happens to be a
first and therefore default value for the enum. So the snippet below will set
value of the ‘isDefault’ Boolean to ‘true’.
'True' Case
SimpleEnum simpleEnum = SimpleEnum.White;bool
isDefault; /* btw this one is 'false' by default
*/ isDefault = simpleEnum == default(SimpleEnum) ? true : false;
/* default value 'white'
*/
Here we set the value to ‘Red’ and ‘default’ will tell us whether or not this
the default value for this enum type. In this case: ‘false’.
'False' Case
simpleEnum = SimpleEnum.Red; /* change from default */isDefault = simpleEnum == default(SimpleEnum) ? true : false;
/* value is not default any longer
*/
Same 'default' functionality can also be applied to DateTimes, value types and other custom types as well.
Sweet ‘n Short. Happy Coding!