Geeks With Blogs
Alex's Blog-o-monium

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
  1. namespace xxx.Common.Domain
  2. {
  3.     public enum SimpleEnum
  4.     {
  5.         White = 1,
  6.  
  7.         Black = 2,
  8.  
  9.         Red = 3
  10.     }
  11. }

 

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
  1. SimpleEnum simpleEnum = SimpleEnum.White;
  2. bool isDefault; /* btw this one is 'false' by default */
  3.  
  4. 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
  1. simpleEnum = SimpleEnum.Red; /* change from default */
  2. 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!

Posted on Friday, April 6, 2012 12:23 AM | Back to top

Copyright © Strenium | Powered by: GeeksWithBlogs.net