-2

Let's say I have:

string ValueToCastTo;
object TheThing;

If ValueToCastTo is set to "int", I want TheThing to be casted to an int. If ValueToCastTo is set to "DateTime", I want TheThing to be casted to a DateTime.

I can't use if statements because the string could be set to anything.

Thanks.

  • 5
    That sounds like a very bad idea. What problem are you trying to solve? – SLaks Dec 14 '15 at 23:07
  • Keep in mind here that you can't actually cast an object to anything you want. "Object" is a base level abstraction. You can only cast TheThing to whatever that object actually is, one of the parents of what that object actually is (which would include "object"), or an interface it implements. – MutantNinjaCodeMonkey Dec 14 '15 at 23:08
  • I need to convert the value of the `ValueToCastTo` into a type so that I can use that to cast the `Object` –  Dec 14 '15 at 23:40
  • @MutantNinjaCodeMonkey I can't cast an empty object to something else, then set the properties using reflection? –  Dec 14 '15 at 23:42
  • If you're going to be using reflection, why don't you just create the specific kind of object you need? – MutantNinjaCodeMonkey Dec 14 '15 at 23:53

3 Answers3

2

You'll need:

Maybe the runtime will figure out the right conversion, but normally it won't. So also write a whole lot of TypeConverter implementations and then use

and when you're done, the static type will still be object. But it'll be a handle to an instance of your new type. Whether that helps you depends on exactly what you want to do with it...

Ben Voigt
  • 277,958
  • 43
  • 419
  • 720
0

TypeOf() you can use to get the type and then do reflection.

"C# - Reflection objects are used for obtaining type information at runtime. The classes that give access to the metadata of a running program are in the System.Reflection namespace."

You can follow that path to get what you want.

Hope that helps!

Manuel
  • 366
  • 2
  • 7
  • Something similar as it explains in this thread. http://stackoverflow.com/questions/12234097/how-to-cast-object-to-its-actual-type – Manuel Dec 14 '15 at 23:05
0

Short answer: you can't.

A cast is something you have to write at compile time, to assign a variable of type X an object of type Y. A cast imply that you know at compile time the type you want to assign to, so you can write something such

int x = (int) y;
string x = (string) y;

There are workarounds to this: use TypeOf() on your object, use reflection to detect at runtime type, properties and methods of the object, or use dynamic to avoid compile time checks.

But it actually depends on what you are trying to get from your code.

Gian Paolo
  • 4,161
  • 4
  • 16
  • 34