I have made a program in which i wanted to convert all values depending on parameters type which is get by run time methods, what i want is convert all values which are enter by user in textbox in define type of parameter. what i wanted is
private object convertType(Type type, string value)
{
Type t = typeof(int);
//suppose value have stringvalue=33;
return 33; //of type int
}
is there any way to get any object type ?
Updated Answer
for @Atmane EL BOUACHRI,
class Program
{
static void Main()
{
var ints = ConvertType<int>("33");
var bools = ConvertType<bool>("false");
var decimals = ConvertType<decimal>("1.33m"); // exception here
Console.WriteLine(ints);
Console.WriteLine(bools);
Console.WriteLine(decimals);
Console.ReadLine();
}
public static T ConvertType<T>(string input)
{
T result = default(T);
var converter = TypeDescriptor.GetConverter(typeof(T));
if (converter != null)
{
try
{
result = (T)converter.ConvertFromString(input);
}
catch
{
// add you exception handling
}
}
return result;
}
}
Here I don't want hard code <int>, <string> or <decimal>, what I want is
private object convertToAnyType(Type type, string value)
{
//Type t = typeof(int);
return ConvertType<type>("33");
}
Is there any way??
Convert.ChangeTypewill work for a limited range of built-in types