0

I need to make a cast with a type passed into a variaable, this is possible ? if yes, how to do this ?

Inside of ForEach action I need to make the cast, I don't have the type, but just a instance of object....

for example: ( of course this is just a hypothetical example to show what I'm trying to do )

private static void ForEach(Type[] tp, Action<string, Type> action)
    {
        for (int i = 0; i < tp.Length; i++)
            action("test", tp[i]);
    }

    static void Main()
    {
        Type[] tp = new Type[]
        {
            typeof(int),
            typeof(string),
            typeof(double)
        };

        ForEach(tp, (x, y) =>
            {
                // make the cast here
                // var aaaa = (y)(x); 
            });
    }

    static T Cast<T>(object input)
    {
        return (T)input;
    }
Alexandre
  • 1,985
  • 5
  • 30
  • 55
  • You want to cast `string` to a given `Type`? Do you know if there are explicit conversions between the types? – Yuval Itzchakov Jul 27 '15 at 17:01
  • @YuvalItzchakov In my method I make all validations... and is possible to make all the correct conversations... – Alexandre Jul 27 '15 at 17:03
  • You'd have to check what the type was for each scenario I believe. – Adam Jul 27 '15 at 17:03
  • Convert.ChangeType ? – dmeglio Jul 27 '15 at 17:07
  • 1
    @dman2306 `Convert.ChangeType` only works on types that implement the `IConvertible` interface. That may be true in the short example, but would fail with types that don't implement it. – Ron Beyer Jul 27 '15 at 17:09
  • possible duplicate of [How to cast object to type described by Type class?](http://stackoverflow.com/questions/1206148/how-to-cast-object-to-type-described-by-type-class) – M.kazem Akhgary Jul 27 '15 at 17:15
  • Hi, I try this posssible solution, but not work... my type is a Enum – Alexandre Jul 27 '15 at 17:36
  • If you need to convert strings to an arbitrary type, look at [this question][1]. [1]: http://stackoverflow.com/questions/2922855/how-to-convert-string-to-any-type – Charles Jul 27 '15 at 17:37
  • Hi :)... is not to a string... – Alexandre Jul 27 '15 at 17:38
  • Are you sure you mean casting and not creating an instance of a certain type? For casting you need an object to cast, and you don't have an object here, just an array of types... – tzachs Jul 27 '15 at 19:52

0 Answers0