0

I have a variable with object type that contain, how example string value, and Type variable that contain string type. I gave a string as an example, but in general a type variable can contain any type that is the type of a variable.

var result = MethodThatDoingSomething(); //return the tuple (Type, object)

//Variables just for better understanding

Type typeResult = result.Item1;
object valueResult = result.Item2;

var typedValue = valueResult as typeResult; //here i got an error
//Cannot resolve symbol 'typeResult'

I tried and next realization and got same error

var typedValue = (typeResult)valueResult;
//Cannot resolve symbol 'typeResult'

And I don't quite understand how to solve this problem...

Claus Stolz
  • 358
  • 4
  • 18
  • Why not use `GetType()`? If you want to do this then use [typeof](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/operators/type-testing-and-cast#typeof-operator) – JTIM Dec 27 '21 at 15:42
  • I tried GetType() too, and got same error – Claus Stolz Dec 27 '21 at 15:43
  • 5
    Casting is purely a compile-time function (telling the compiler to interact with the object as an object of the casted type. There's no point in casting if you don't know the type at compile-time. – D Stanley Dec 27 '21 at 15:43
  • 1
    `var typedValue` if you don't know the type if the variable until runtime, what is the point of casting it? What do you hope to achieve by casting it? Perhaps you can cast it to an interface or something? – Charlieface Dec 27 '21 at 15:43
  • 3
    To be more constructive, what do you plan to _do_ with the typed object after you cast? There may be a better way to do _that_. – D Stanley Dec 27 '21 at 15:44
  • Else you have to start looking into `dynamic` if this is really what you want – JTIM Dec 27 '21 at 15:45
  • 1
    You might want to look at https://stackoverflow.com/questions/972636/casting-a-variable-using-a-type-variable – Progman Dec 27 '21 at 15:45
  • Or this https://stackoverflow.com/questions/4925718/c-dynamic-runtime-cast – JTIM Dec 27 '21 at 15:47
  • It's true that `dynamic` lets you do some weird stuff, but I strongly recommend not going down that path. 99.99% of the time it's just an issue with figuring out the language and understanding how to write the code so that we don't need to do stuff like this at runtime. We can almost always write code so that we know what the type is and don't have to do anything odd. It's just a matter of getting over the hump to where it makes sense and we know how to do that. – Scott Hannen Dec 27 '21 at 16:19

0 Answers0