What’s ‘default’ for?
Posted
by Strenium
on Geeks with Blogs
See other posts from Geeks with Blogs
or by Strenium
Published on Fri, 06 Apr 2012 04:23:23 GMT
Indexed on
2012/04/06
11:30 UTC
Read the original article
Hit count: 229
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'
- 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’.
- 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’.
- 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!
© Geeks with Blogs or respective owner