How to return default value from Generic Method

29 Apr 2014, 03:30 AM

In generic classes there are scenarios where we need to return the object. Suppose we are creating generic class for cache and we have Get method in it. If data exist in cache we will return that otherwise we will return default value. But in generic we don’t exactly knows the type of the variables. The variable can be a value type or reference type. In this situation how could we know the default value of the class? Dot Net provides a default(ClassName) method to get the default value of the object or class. e.g

 public class MyCache<T> 
   public T Get(string key) 
       if (_memoryCache.Contains(key)) 
          var cacheObject = (T)_memoryCache.Get(key); 
         return cacheObject; 
       return default(T); 

Related Contents

15 May 2014, 08:07 AM
C#, LINQ, List
15 May 2014, 07:54 AM
C#, LINQ, List
29 Apr 2014, 02:51 AM
C#, Generic
Explains how to return the default value of Generic variable T, when T can be a value type or reference type.

Date Posted 29 Apr 2014, 03:07 AM
Author Brainy Solutions
Views 2,453