Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert variable to type only known at run-time?

Tags:

c#

foreach (var filter in filters) {     var filterType = typeof(Filters);     var method = filterType.GetMethod(filter, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Static);     if (method != null)     {         var parameters = method.GetParameters();         Type paramType = parameters[0].ParameterType;         value = (string)method.Invoke(null, new[] { value });     } } 

How can I cast value to paramType? value is a string, paramType will probably just be a basic type like int, string, or maybe float. I'm cool with it throwing an exception if no conversion is possible.

like image 940
mpen Avatar asked Oct 24 '10 19:10

mpen


People also ask

How to explicitly cast?

A cast is a way of explicitly informing the compiler that you intend to make the conversion and that you are aware that data loss might occur, or the cast may fail at run time. To perform a cast, specify the type that you are casting to in parentheses in front of the value or variable to be converted.

What does cast do in C#?

Cast, in the context of C#, is a method by which a value is converted from one data type to another. Cast is an explicit conversion by which the compiler is informed about the conversion and the resulting possibility of data loss.

How do you cast a type?

Typecasting is making a variable of one type, such as an int, act like another type, a char, for one single operation. To typecast something, simply put the type of variable you want the actual variable to act as inside parentheses in front of the actual variable. (char)a will make 'a' function as a char.


1 Answers

The types you are using all implement IConvertible. As such you can use ChangeType.

 value = Convert.ChangeType(method.Invoke(null, new[] { value }), paramType); 
like image 129
Aliostad Avatar answered Oct 09 '22 11:10

Aliostad