Generic Code with Default Keyword
One of issues we face when we work with generic classes and methods is
- How to assign default value for T
- 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.
- public static T Get<T>(string key)
- {
- DataCache defaultCache = GetDataCache();
- T value = default(T);
- var cacheValue = defaultCache.Get(key);
- if (cacheValue != null)
- {
- try
- {
- value = (T) defaultCache.Get(key);
- }
- catch
- {
- value = default(T);
- }
- }
- return value;
- }
Happy Coding!!!!
Comments
Post a Comment