0

How to cast using type variable ? consider below code

public static object As(object o1, Type t1)
{
  return (t1)o1;
}

But it is showing me an error that t1 is a variable and is used as type. how can i achieve this purpose.Is it possible to retrieve the type from type object.I was asked to implement is and as operators in c# hence the method name.

123
  • 41
  • 8

1 Answers1

1

Try this:

public static T Cast<T>(object obj, Type castTo) 
{ 
     return (T)Convert.ChangeType(obj, castTo); 
}

An example works :

https://dotnetfiddle.net/JqFMds

Antoine V
  • 6,998
  • 2
  • 11
  • 34
  • 2
    If you instead of `dynamic`, pass `object` and do `T Cast(object obj, Type castTo) { return (T)Convert.ChangeType(obj, castTo); }` then you don't need to return `dynamic`. – FCin Jul 02 '18 at 12:05
  • Thanks. I updated the anwser – Antoine V Jul 02 '18 at 12:09
  • is there a way other than generics. – 123 Jul 02 '18 at 12:11
  • @NagasivaniSiddana : you can use this version : https://dotnetfiddle.net/E4ervV , with dynamic . But I think my answer is more elegant – Antoine V Jul 02 '18 at 12:13
  • It is showing an error that object should implement Iconvertable interface – 123 Jul 02 '18 at 12:21
  • @NagasivaniSiddana can you check your code because the method in the anwser doesn't need IConvertable interface. Look on the code dotnetfiddle, it works – Antoine V Jul 02 '18 at 12:25
  • I am using it for the user defined classes .i am trying change the derived type to base and it is me that error – 123 Jul 02 '18 at 12:34
  • This generic solution seems a bit weird - if you have the type `T` as a compile time value then what is the point of the `castTo` parameter? – Chris Jul 02 '18 at 12:44
  • @Thierry https://dotnetfiddle.net/x1BWB3 – 123 Jul 02 '18 at 12:46
  • @NagasivaniSiddana : because of the user-defined typed, if you want to convert Devired to Program, you need to define the convertion of 2 types (by IConvertible interface) .... – Antoine V Jul 02 '18 at 13:07