Friday, March 27, 2020

c# method to return dynamic types

This is a simple method that return dynamic types based on what it recieves from the parameter.

 private dynamic GetValue<T>(object value, bool toString)  
     {  
       Type type = typeof(T);  
       if (value == null || (value != null && string.IsNullOrEmpty(value.ToString())))  
       {  
         if (toString)  
           return string.Empty;  
         else  
           return null;  
       }  
       else  
       {  
         if (toString)  
           return value.ToString();  
         else  
           return Convert.ChangeType(value, type);  
       }  
     }  

value : the value you want to get
toString : whether the return type needs to be as a string.

example,
 item.EXT_PRODUCT_ID = this.GetValue<int?>(p.idProduct, true);  

The value we pass is
p.idProduct

and it is a nullable integer. Also we set toString as true. so the return value is :
"466565" or empty string.

Instead of checking null everytime, we can use this method.

Happy coding.

No comments:

Post a Comment