Enhance String type to get Converted In Given TypeProblem
Recently I was working on the project where I need to read the excel file data and have to convert data of it in strong entity which is consist of number of property. For this I know the sequence of the data in excel file and name & type of property of the entity which is going to store the value. But the real problem is I need to convert the string value in property type.
Solution
One of the solution to this is create function and pass the type & string value which
return data in type which is passed. Below is implementation function
public static T ConvertData<T>(this string s)
{
if(!sting.IsNullOrEmpty(s))
{
if (typeof(T) == typeof(System.Decimal))
{
return (T)(object)Convert.ToDecimal(s);
}
}
//same code get replicated for int, float etc.
return default(T);
}
In above code I created on generic extension method for string type. Function convert string type to the type I want.
Cons
- In above implementation I written code for Decimal type but same code I have to replicate for other types also i.e for int, float etc.
- As you see in code after converting data in given type I again need to reconvert into object and than into type T again. This also add overhead of type casting.
- Code is become long and unclear.
So to make code clean , clear and easy to understand. I fond one method in C#.net which is Convert.ChangeType which helps me to create the method i want easily.
Below is my Simpler and easy solution
public static T ConvertData<T>(this string s)
{
if(!sting.IsNullOrEmpty(s))
{
return (T)Convert.ChangeType(s, typeof(T),null);
}
return default(T);
}
So in above solution I just need to write one line of the code which do the task for me.
Actual syntax of method is
public static Object ChangeType(
Object value,
Type conversionType,
IFormatProvider provider
)
As you can see in syntax third parameter is provider which is null in my case but you can pass the formater by creating as you need.
Now following code is just show how to use this method in code i.e ConvertData method
string s = "123";
int a = s.ConvertData<int>();
So this method can be used any project and also fit in number of requirement.