Tuesday, April 29, 2014

Generic Code with Default Keyword

 

One of issues we face when we work with generic classes and methods is

  1. How to assign default value for T
  2. How to return Null in a Generic method

This is because T could be a reference type or a numeric value or struct.

because T=null is not valid for numeric and structs even it is valid for reference type.

Default keyword is the solution for it. It will return the default value of T.

  1. public static T Get<T>(string key)
  2.         {
  3.             DataCache defaultCache = GetDataCache();
  4.             T value = default(T);
  5.             var cacheValue = defaultCache.Get(key);
  6.  
  7.             if (cacheValue != null)
  8.             {
  9.                 try
  10.                 {
  11.                     value = (T) defaultCache.Get(key);
  12.                 }
  13.  
  14.                 catch
  15.                 {
  16.                     value = default(T);
  17.                 }
  18.             }
  19.             return value;
  20.  
  21.         }

Happy Coding!!!!

No comments :

Post a Comment