Generic string to primitive type converter in C#
Converting string data to any primitive type in .NET and .NET Core
Often case when you need to convert String to a different type which is most of the time a primitive type in C# is when you are reading values from configuration. In both .NET and .NET Core, reading from configuration return plain String value. You can easily convert it, but causes a code repetition especially if you are handling the exception.
Over time you end up with a lot of try/catch block and you code looks like spaghetti.
Good part is that most of the types you often convert from configuration implement IConvertible interface. That is common for both int34, int64, bool, byte which are most common types you store in the configuration.
public struct Int32 : IComparable, IComparable<Int32>, IConvertible, IEquatable<Int32>, IFormattable public struct Int64 : IComparable, IComparable<Int64>, IConvertible, IEquatable<Int64>, IFormattable public struct Boolean : IComparable, IComparable<Boolean>, IConvertible, IEquatable<Boolean> public struct Byte : IComparable, IComparable<Byte>, IConvertible, IEquatable<Byte>, IFormattable public sealed class String : IEnumerable<char>, IEnumerable, IComparable, IComparable<String>, IConvertible, IEquatable<String>, ICloneable
From the code snippets above which I got by going to type definition in VisualStudio, you see that common implemented interface is IConvertible.
We can see this as a generic interface to perform casting to desired type. the best way to extend functionality in .NET is by using extension methods, so I did that for IConfiguration interface in .NET Core
.NET Core
namespace Core.Common.Extensions { public static class Configuration { public static T Get<T>(this IConfiguration configuration,String key) where T:IConvertible { return (T)Convert.ChangeType(configuration[key], typeof(T)); } } }
.NET
In .NET this would be an extension to System.Configuration.ConfigurationManager class but since it is a static class we need to add extension to AppSetting property which is of type NameValueCollection, so we add it for this type
namespace Common.Extensions { public static class Configuration { public static T Get<T>(this NameValueCollection configuration, String key) where T : IConvertible { return (T)Convert.ChangeType(configuration[key], typeof(T)); } } }
And gettint the value would be like
System.Configuration.ConfigurationManager.AppSettings.Get<int>("MyIntConfigKey")
Disclaimer
Purpose of the code contained in snippets or available for download in this article is solely for learning and demo purposes. Author will not be held responsible for any failure or damages caused due to any other usage.
Comments for this article