Accessing static values from resource files or other external files such as XML is common in programming. An example is accessing a value such as a ConnectionString or any other statuc value from AppSettings in the config file.
However in large applications we will prefer to have this within a static method or as a property in some utility class which we can call from different parts of the application’s code. Here is a performance effective way to code this in a method
object Val = ConfigurationManager.AppSettings[key];
if(Val == null)
return (T) Convert.ChangeType(Val, typeof(T));
apart from reusability of this piece of code, an obvious benefit is that we will not have to do any further type casting as we are the method returns the desired data type. Here are some examples of how you can use it
private long AccountNum = 0;
private string Email = "";
private void Page_Load(object sender, EventArgs e)
PortNumber = GetAppSettingValue<int>("PortNumber", 25);
Email = GetQueryStringValue<string>("EmailAddress", "email@example.com");
AccountNum = GetQueryStringValue<long>("AccountNumber", 0);
Isn’t that much better? And we can of course apply a similar logic for accessing QueryString Values, Cookies, Session Variables etc.