Configuration reader with generic type casting C# with Example



Configuration reader with generic type casting C# with Example

///  
/// Read configuration values from app.config and convert to specified types 
///  
public static class ConfigurationReader 
{ 
///  
/// Get value from AppSettings by key, convert to Type of default value or typeparam T and 
return 
 

///  
/// typeparam is the type in which value will be returned, it could be 
any type eg. int, string, bool, decimal etc. 
/// key to find value from AppSettings 
/// defaultValue will be returned in case of value is null or any 
exception occures 
/// AppSettings value against key is returned in Type of default value or given as 
typeparam T 
public static T GetConfigKeyValue(string strKey, T defaultValue) 
{ 
var result = defaultValue; 
try 
{ 
if (ConfigurationManager.AppSettings[strKey] != null) 
result = (T)Convert.ChangeType(ConfigurationManager.AppSettings[strKey], 
typeof(T)); 
} 
catch (Exception ex) 
{ 
Tracer.Current.LogException(ex); 
} 
return result; 
} 
 ///  
/// Get value from AppSettings by key, convert to Type of default value or typeparam T and 
return 
///  
/// typeparam is the type in which value will be returned, it could be 
any type eg. int, string, bool, decimal etc. 
/// key to find value from AppSettings 
/// AppSettings value against key is returned in Type given as typeparam T 
public static T GetConfigKeyValue(string strKey) 
{ 
return GetConfigKeyValue(strKey, default(T)); 
} 
} 
Usages: 
var timeOut = ConfigurationReader.GetConfigKeyValue("RequestTimeout", 2000); 
var url = ConfigurationReader.GetConfigKeyValue("URL", "www.someurl.com"); 
var enabled = ConfigurationReader.GetConfigKeyValue("IsEnabled", false); 
 

Provides a convenient syntax that ensures the correct use of IDisposable objects. 

0 Comment's

Comment Form

Submit Comment