Reputation: 1607
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??
Upvotes: 0
Views: 1270
Reputation:
You mean certainly return string value parsed to a specific Type. Then , I propose generics. Here's how :
1)- Without Generics (I Prefer With Generic in 2)-)
class Program
{
static void Main()
{
var ints = (int)ConvertType(typeof(int),"33");
var bools = (bool)ConvertType(typeof(bool), "true");
Console.WriteLine(bools);
Console.WriteLine(ints);
Console.ReadLine();
}
public static object ConvertType(Type type, string input)
{
object result = default(object);
var converter = TypeDescriptor.GetConverter(type);
if (converter != null)
{
try
{
result = converter.ConvertFromString(input);
}
catch
{
// add you exception handling
}
}
return result;
}
}
2)-With Generic
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;
}
}
Hpe it helps
Upvotes: 1