Casting objects to types have sense only in compile time. How you would react to the casted object in your code?
The object already has it's "original" type. The case is, when you threat it as an object
you don't know its type in compile time. In runtime of course it will act as it is the "original" type you call.
Suppose you have a class, that overrides ToString()
method:
public class Foo
{
public override string ToString() { return "I am foo"; }
}
Then you have a piece of code:
Foo foo = new Foo();
object obj = foo;
// obj is of course Foo type
Console.Write(obj.ToString());
It will of course result in writing "I am foo" to the console, because the variable obj
is of type Foo
, and it will act properly.
Then suppose we have a class:
public class Bar
{
public override string ToString() { return "I am bar"; }
public void Foobar() {}
}
And piece of not real code that you wish to have:
object obj = new Bar();
// your runtime type casting here:
var casted = (obj.GetType()) obj;
Question is: what will you do with your casted
variable? Can you call method Foobar()
? How will you know if you can call method Foobar()
in compile time, when you don't know the type?
Maybe the thing you seek is polymorphism? Maybe reflection? Maybe dynamic objects?
EDIT: From what you say, you need a reflection, a mechanism for investigating types in runtime. See this:
var type = obj.GetType();
var props = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
foreach(var prop in props)
{
Console.WriteLine("property: {0} type:{1}", prop.Name, prop.PropertyType);
}